parseQuery.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const JSON5 = require('json5');
  3. const specialValues = {
  4. null: null,
  5. true: true,
  6. false: false,
  7. };
  8. function parseQuery(query) {
  9. if (query.substr(0, 1) !== '?') {
  10. throw new Error(
  11. "A valid query string passed to parseQuery should begin with '?'"
  12. );
  13. }
  14. query = query.substr(1);
  15. if (!query) {
  16. return {};
  17. }
  18. if (query.substr(0, 1) === '{' && query.substr(-1) === '}') {
  19. return JSON5.parse(query);
  20. }
  21. const queryArgs = query.split(/[,&]/g);
  22. const result = Object.create(null);
  23. queryArgs.forEach((arg) => {
  24. const idx = arg.indexOf('=');
  25. if (idx >= 0) {
  26. let name = arg.substr(0, idx);
  27. let value = decodeURIComponent(arg.substr(idx + 1));
  28. if (specialValues.hasOwnProperty(value)) {
  29. value = specialValues[value];
  30. }
  31. if (name.substr(-2) === '[]') {
  32. name = decodeURIComponent(name.substr(0, name.length - 2));
  33. if (!Array.isArray(result[name])) {
  34. result[name] = [];
  35. }
  36. result[name].push(value);
  37. } else {
  38. name = decodeURIComponent(name);
  39. result[name] = value;
  40. }
  41. } else {
  42. if (arg.substr(0, 1) === '-') {
  43. result[decodeURIComponent(arg.substr(1))] = false;
  44. } else if (arg.substr(0, 1) === '+') {
  45. result[decodeURIComponent(arg.substr(1))] = true;
  46. } else {
  47. result[decodeURIComponent(arg)] = true;
  48. }
  49. }
  50. });
  51. return result;
  52. }
  53. module.exports = parseQuery;