import * as path from 'path' ; import { Resource } from '../type/resource' ; import * as qs from 'querystring' ; import { map , sort , pipe , join , ascend , omit , pick } from 'ramda' ; import { compact } from 'ramda-adjunct' ; import { compactObject } from './util' ; import * as url from 'url' ; const commonQueryStringify = pipe ( Object . entries , map ( ( [ key , value ] ) => { if ( typeof value === 'boolean' ) { return value ? key : '' ; } return `${ key }=${ qs . escape ( value ) }` ; } ) , compact , sort ( ascend ( v => v ) ) , join ( '&' ) ) ; const uriQueryStringify = pipe ( omit ( [ 'bucket' , 'objectKey' ] ) , commonQueryStringify ) ; const resourceQueryStringify = pipe ( pick ( [ 'acl' , 'location' , 'uploadId' , 'uploads' , 'partNumber' , 'delete' ] ) , commonQueryStringify ) ; param key export function escapeObjectKey ( key ) { return key . replace ( /\//g , '%2F' ) ; } param resource export function getResourceUri ( resource ) { if ( typeof resource === 'string' ) return resource ; const query = uriQueryStringify ( resource ) ; const urlObj = { pathname : '/' , search : query , } ; if ( 'objectKey' in resource ) { urlObj . pathname = url . resolve ( urlObj . pathname , resource . objectKey ) ; } return url . format ( urlObj ) ; } param resource export function getResourceString ( resource ) { if ( typeof resource === 'string' ) return resource ; const query = resourceQueryStringify ( resource ) ; if ( 'objectKey' in resource ) { return url . format ( { pathname : path . posix . join ( '/' , resource . bucket , escapeObjectKey ( resource . objectKey ) ) , search : query , } ) ; } else if ( 'bucket' in resource ) { return `/${ resource . bucket }/${ query ? '?' + query : '' }` ; } return '/' ; } export function mergeResource ( dest , ... srcs ) { Object . assign ( dest , ... srcs . map ( compactObject ) ) ; }