Front end of the Slack clone application.

parseQuery.js 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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("A valid query string passed to parseQuery should begin with '?'");
  11. }
  12. query = query.substr(1);
  13. if(!query) {
  14. return {};
  15. }
  16. if(query.substr(0, 1) === "{" && query.substr(-1) === "}") {
  17. return JSON5.parse(query);
  18. }
  19. const queryArgs = query.split(/[,&]/g);
  20. const result = {};
  21. queryArgs.forEach(arg => {
  22. const idx = arg.indexOf("=");
  23. if(idx >= 0) {
  24. let name = arg.substr(0, idx);
  25. let value = decodeURIComponent(arg.substr(idx + 1));
  26. if(specialValues.hasOwnProperty(value)) {
  27. value = specialValues[value];
  28. }
  29. if(name.substr(-2) === "[]") {
  30. name = decodeURIComponent(name.substr(0, name.length - 2));
  31. if(!Array.isArray(result[name]))
  32. result[name] = [];
  33. result[name].push(value);
  34. } else {
  35. name = decodeURIComponent(name);
  36. result[name] = value;
  37. }
  38. } else {
  39. if(arg.substr(0, 1) === "-") {
  40. result[decodeURIComponent(arg.substr(1))] = false;
  41. } else if(arg.substr(0, 1) === "+") {
  42. result[decodeURIComponent(arg.substr(1))] = true;
  43. } else {
  44. result[decodeURIComponent(arg)] = true;
  45. }
  46. }
  47. });
  48. return result;
  49. }
  50. module.exports = parseQuery;