-
Notifications
You must be signed in to change notification settings - Fork 1
/
generator.js
51 lines (42 loc) · 1.4 KB
/
generator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const pathToRegexp = require("path-to-regexp");
export const uri = (route, params = {}) => {
if (typeof params !== "object") {
throw new RouteException(
`Error on route ${route}. Route params should be an object, ${typeof params} given.`
);
}
if (Object.keys(params).length === 0 || Object.values(params).every(o => o === undefined)) {
return optionalParams => concatOptionalParams(route, optionalParams);
}
const toPath = pathToRegexp.compile(route);
try {
const compiledUrl = toPath(params);
return optionalParams => concatOptionalParams(compiledUrl, optionalParams);
} catch (e) {
throw new RouteException(`Error on route ${route}. ${e.message}`);
}
};
export const serializeObjectToQueryString = (obj = {}) => {
let str = [];
for (const p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
};
export const concatOptionalParams = (uri, params = {}) => {
if (typeof params !== "object")
throw new RouteException(
`Error on route ${uri}. Optional route params should be an object, ${typeof params} given.`
);
if (!params || Object.keys(params).length <= 0) {
return uri;
}
return uri + "?" + serializeObjectToQueryString(params);
};
class RouteException {
constructor(message) {
this.name = "Route exception.";
this.message = message;
}
}