Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. // It's just simplified Qs, only supports primitive value except Symbol
  2.  
  3. function isPlainObject (o) { return Object.prototype.toString.call(o) === '[object Object]' }
  4.  
  5. function isString (o) { return Object.prototype.toString.call(o) === '[object String]' }
  6.  
  7. export function stringify (query, { addQueryPrefix = false } = {}) {
  8. if (!isPlainObject(query)) {
  9. return ''
  10. }
  11.  
  12. return Object.keys(query)
  13. .reduce(
  14. (querystring, property) => {
  15. if (query[property] === void 0) { /* skip undefined */
  16. return querystring
  17. }
  18.  
  19. return querystring + '&' + encodeURIComponent(property) + '=' + encodeURIComponent(query[property])
  20. },
  21. ''
  22. )
  23. .replace(/^&/, addQueryPrefix ? '?' : '')
  24. }
  25.  
  26. const BOOLEAN_STRINGS = [ 'false', 'true' ]
  27. export function parse (querystring, { ignoreQueryPrefix = false } = {}) {
  28. if (!isString(querystring)) {
  29. return {}
  30. }
  31.  
  32. return querystring
  33. .replace(/^\?/, ignoreQueryPrefix ? '' : '$&')
  34. .split('&')
  35. .reduce(
  36. (query, string) => {
  37. const [ property, value ] = string
  38. .split('=')
  39. .map((string = '') => decodeURIComponent(string))
  40.  
  41. if (!!~BOOLEAN_STRINGS.indexOf(value)) {
  42. query[property] = !!BOOLEAN_STRINGS.indexOf(value)
  43. } else {
  44. query[property] = value
  45. }
  46.  
  47. return query
  48. },
  49. {}
  50. )
  51. }
  52.  
  53. export default {
  54. stringify,
  55. parse
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement