Projekt

Obecné

Profil

Stáhnout (1.43 KB) Statistiky
| Větev: | Revize:
1 3a515b92 cagy
'use strict';
2
3
const JSON5 = require('json5');
4
5
const specialValues = {
6
  null: null,
7
  true: true,
8
  false: false,
9
};
10
11
function parseQuery(query) {
12
  if (query.substr(0, 1) !== '?') {
13
    throw new Error(
14
      "A valid query string passed to parseQuery should begin with '?'"
15
    );
16
  }
17
18
  query = query.substr(1);
19
20
  if (!query) {
21
    return {};
22
  }
23
24
  if (query.substr(0, 1) === '{' && query.substr(-1) === '}') {
25
    return JSON5.parse(query);
26
  }
27
28
  const queryArgs = query.split(/[,&]/g);
29
  const result = {};
30
31
  queryArgs.forEach((arg) => {
32
    const idx = arg.indexOf('=');
33
34
    if (idx >= 0) {
35
      let name = arg.substr(0, idx);
36
      let value = decodeURIComponent(arg.substr(idx + 1));
37
38
      if (specialValues.hasOwnProperty(value)) {
39
        value = specialValues[value];
40
      }
41
42
      if (name.substr(-2) === '[]') {
43
        name = decodeURIComponent(name.substr(0, name.length - 2));
44
45
        if (!Array.isArray(result[name])) {
46
          result[name] = [];
47
        }
48
49
        result[name].push(value);
50
      } else {
51
        name = decodeURIComponent(name);
52
        result[name] = value;
53
      }
54
    } else {
55
      if (arg.substr(0, 1) === '-') {
56
        result[decodeURIComponent(arg.substr(1))] = false;
57
      } else if (arg.substr(0, 1) === '+') {
58
        result[decodeURIComponent(arg.substr(1))] = true;
59
      } else {
60
        result[decodeURIComponent(arg)] = true;
61
      }
62
    }
63
  });
64
65
  return result;
66
}
67
68
module.exports = parseQuery;