import URL from 'url' ; import { SimpleReq , ParsedUrl , SimpleResp } from './interface' ; import { isString } from 'lodash/fp' ; export function sleep ( millisecond ) { return new Promise ( ( resolve ) => { setTimeout ( resolve , millisecond ) ; } ) ; } export function parseUrl4Req ( req ) { const u = URL . parse ( req . url ) ; const url = { origin : null , ... u } ; if ( url . protocol && url . host ) { url . origin = `${ url . protocol }//${ url . host }` ; url . shortHref = `${ url . origin }${ url . pathname }` ; return url ; } url . host = req . headers . host ; url . protocol = 'https:' ; url . origin = `${ url . protocol }//${ url . host }` ; url . shortHref = `${ url . origin }${ url . pathname }` ; url . href = `${ url . shortHref }${ url . search || '' }${ url . hash || '' }` ; return url ; } /**
 * 尝试将任意对象解析为JSON对象，如果解析失败则返回原对象，不会抛出错误
 */ export function safeJSONParse ( val ) { if ( ! isString ( val ) ) return val ; try { return JSON . parse ( val ) ; } catch ( e ) { return val ; } } param resp export function isTextResp ( resp ) { const ct = resp . headers [ 'content-type' ] || resp . headers [ 'Content-Type' ] ; if ( ! ct ) return false ; return /text|json|javascript|xml|svg|csv|html?|css/ . test ( ct ) ; }