UNPKG

@platform/cell.schema

Version:

URI and database schemas for the `cell.os`.

61 lines (60 loc) 2.13 kB
import { defaultValue, R } from '../common'; export class Url { constructor(args) { this._ = { query: {}, querystring: '', }; this.origin = (args.origin || '').trim().replace(/\/*$/, ''); this.path = `/${(args.path || '').trim().replace(/^\/*/, '')}`; this._.query = args.query || {}; this._.querystring = typeof args.querystring === 'string' ? args.querystring.trim() : ''; } get querystring() { const text = (this._.querystring || '').replace(/^\?*/, ''); const query = this._.query || {}; let res = ''; const format = (value) => { value = typeof value === 'string' ? value.trim() : value; return value; }; const append = (key, value) => { res = res ? `${res}&` : res; res = value === undefined ? `${res}${key}` : `${res}${key}=${value}`; }; Object.keys(query).forEach(key => { const value = query[key]; if (typeof value !== 'function' && value !== undefined && value !== '') { if (Array.isArray(value)) { const values = value.map(value => format(value)); R.uniq(values).forEach(value => append(key, value)); } else { append(key, format(value)); } } }); if (text) { res = res ? `${res}&${text}` : text; } return res ? `?${res}` : ''; } query(input) { const querystring = this._.querystring || ''; let query = this._.query || {}; if (typeof input === 'object') { query = Object.assign(Object.assign({}, query), input); } return new Url({ origin: this.origin, path: this.path, query, querystring, }); } toString(options = {}) { const origin = defaultValue(options.origin, true); const path = `${this.path}${this.querystring}`; return origin ? `${this.origin}${path}` : path; } }