Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // It's just simplified Qs, only supports primitive value except Symbol
- function isPlainObject (o) { return Object.prototype.toString.call(o) === '[object Object]' }
- function isString (o) { return Object.prototype.toString.call(o) === '[object String]' }
- export function stringify (query, { addQueryPrefix = false } = {}) {
- if (!isPlainObject(query)) {
- return ''
- }
- return Object.keys(query)
- .reduce(
- (querystring, property) => {
- if (query[property] === void 0) { /* skip undefined */
- return querystring
- }
- return querystring + '&' + encodeURIComponent(property) + '=' + encodeURIComponent(query[property])
- },
- ''
- )
- .replace(/^&/, addQueryPrefix ? '?' : '')
- }
- const BOOLEAN_STRINGS = [ 'false', 'true' ]
- export function parse (querystring, { ignoreQueryPrefix = false } = {}) {
- if (!isString(querystring)) {
- return {}
- }
- return querystring
- .replace(/^\?/, ignoreQueryPrefix ? '' : '$&')
- .split('&')
- .reduce(
- (query, string) => {
- const [ property, value ] = string
- .split('=')
- .map((string = '') => decodeURIComponent(string))
- if (!!~BOOLEAN_STRINGS.indexOf(value)) {
- query[property] = !!BOOLEAN_STRINGS.indexOf(value)
- } else {
- query[property] = value
- }
- return query
- },
- {}
- )
- }
- export default {
- stringify,
- parse
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement