@miqro/core 1.5.14 → 1.5.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-router.d.ts +6 -5
- package/dist/api-router.js +9 -3
- package/dist/api-router.js.map +1 -1
- package/dist/app-utils.d.ts +13 -0
- package/dist/app-utils.js +82 -0
- package/dist/app-utils.js.map +1 -0
- package/dist/app.js +6 -88
- package/dist/app.js.map +1 -1
- package/dist/common/api-router-utils.d.ts +1 -1
- package/dist/common/api-router-utils.js +7 -3
- package/dist/common/api-router-utils.js.map +1 -1
- package/dist/common/config/config.js +12 -0
- package/dist/common/config/config.js.map +1 -1
- package/dist/common/config/loader.js +2 -2
- package/dist/common/config/loader.js.map +1 -1
- package/dist/common/context.js +6 -3
- package/dist/common/context.js.map +1 -1
- package/dist/common/router-handler.d.ts +20 -0
- package/dist/common/router-handler.js +136 -0
- package/dist/common/router-handler.js.map +1 -0
- package/dist/common/router-utils.d.ts +7 -5
- package/dist/common/router-utils.js +37 -47
- package/dist/common/router-utils.js.map +1 -1
- package/dist/common/session/service.js +4 -1
- package/dist/common/session/service.js.map +1 -1
- package/dist/common/tokenize-match.d.ts +13 -20
- package/dist/common/tokenize-match.js +27 -59
- package/dist/common/tokenize-match.js.map +1 -1
- package/dist/middleware/group.js +2 -0
- package/dist/middleware/group.js.map +1 -1
- package/dist/middleware/index.d.ts +1 -0
- package/dist/middleware/index.js +1 -0
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/result.d.ts +3 -0
- package/dist/middleware/result.js +51 -0
- package/dist/middleware/result.js.map +1 -0
- package/dist/router.d.ts +3 -30
- package/dist/router.js +5 -167
- package/dist/router.js.map +1 -1
- package/package.json +10 -8
- package/src/api-router.ts +16 -7
- package/src/api-router.unit.test.js +273 -0
- package/src/app-utils.ts +82 -0
- package/src/app-utils.unit.test.js +100 -0
- package/src/app.ts +4 -89
- package/src/app.unit.test.js +334 -0
- package/src/common/api-router-utils.ts +6 -3
- package/src/common/config/config.ts +12 -0
- package/src/common/config/loader.ts +2 -2
- package/src/common/context.ts +7 -3
- package/src/common/context.unit.test.js +286 -0
- package/src/common/router-handler.ts +159 -0
- package/src/common/router-utils.ts +46 -44
- package/src/common/session/service.ts +4 -1
- package/src/common/tokenize-match.ts +32 -54
- package/src/middleware/group.ts +2 -0
- package/src/middleware/index.ts +1 -0
- package/src/middleware/result.ts +43 -0
- package/src/proxy.unit.test.js +157 -0
- package/src/router.ts +7 -196
- package/src/router.unit.test.js +397 -0
- package/src/setup-test.js +5 -0
|
@@ -1,45 +1,16 @@
|
|
|
1
1
|
import {URLSearchParams} from "url";
|
|
2
|
-
import {newURLSearchParams} from "./helpers";
|
|
3
2
|
|
|
4
|
-
export
|
|
5
|
-
const query: { [name: string]: string | string[] } =
|
|
3
|
+
export function parseSearchParams(search: URLSearchParams): { [name: string]: string | string[] } {
|
|
4
|
+
const query: { [name: string]: string | string[] } = Object.create(null);
|
|
6
5
|
search.forEach((value: string, key: string) => {
|
|
7
6
|
query[key] = query[key] instanceof Array ? (query[key] as string[]).concat([value]) : query[key] ? [query[key] as string, value] : value;
|
|
8
7
|
});
|
|
9
8
|
return query;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
// appends query params to URLSearchParams and returns a copy
|
|
13
|
-
export const mergeSearchParams = (search: URLSearchParams, append?: { [name: string]: string | string[] | number | boolean | number[] | boolean[] }): URLSearchParams => {
|
|
14
|
-
const copy = newURLSearchParams(search.toString());
|
|
15
|
-
if (!append) {
|
|
16
|
-
return copy;
|
|
17
|
-
}
|
|
18
|
-
const keys = Object.keys(append);
|
|
19
|
-
for (const k of keys) {
|
|
20
|
-
if (append[k] instanceof Array) {
|
|
21
|
-
for (const a of append[k] as Array<any>) {
|
|
22
|
-
if (copy.has(k)) {
|
|
23
|
-
copy.append(k, String(a));
|
|
24
|
-
} else {
|
|
25
|
-
copy.set(k, String(a));
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
} else {
|
|
30
|
-
if (copy.has(k)) {
|
|
31
|
-
copy.append(k, String(append[k]));
|
|
32
|
-
} else {
|
|
33
|
-
copy.set(k, String(append[k]));
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
return copy;
|
|
38
|
-
};
|
|
9
|
+
}
|
|
39
10
|
|
|
40
11
|
// adds "/" to the final of path
|
|
41
12
|
// cannot account for query or hash params so send only new URL().pathname
|
|
42
|
-
export
|
|
13
|
+
export function normalizePath(path: string): string {
|
|
43
14
|
if (typeof path !== "string") {
|
|
44
15
|
throw new Error("path not string");
|
|
45
16
|
}
|
|
@@ -59,33 +30,40 @@ export const normalizePath = (path: string): string => {
|
|
|
59
30
|
}
|
|
60
31
|
}
|
|
61
32
|
|
|
62
|
-
export interface
|
|
33
|
+
export interface PathParams {
|
|
34
|
+
[name: string]: string | undefined
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface PathPartToken extends PathPart {
|
|
63
38
|
optional: boolean;
|
|
64
39
|
wild?: string;
|
|
65
|
-
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface PathPart {
|
|
43
|
+
value: string;
|
|
66
44
|
lower: string;
|
|
67
45
|
}
|
|
68
46
|
|
|
69
|
-
|
|
47
|
+
function pathPartTokenize(token: PathPart): PathPartToken {
|
|
70
48
|
const isWild = token.value[0] === ":";
|
|
71
49
|
const optional = token.value[token.value.length - 1] === "?";
|
|
72
50
|
const wild = isWild ? token.value.substring(1, token.value.length - (optional ? 1 : 0)) : undefined;
|
|
73
51
|
return {
|
|
74
52
|
optional,
|
|
75
53
|
wild,
|
|
76
|
-
|
|
54
|
+
value: token.value,
|
|
77
55
|
lower: token.lower
|
|
78
56
|
}
|
|
79
57
|
}
|
|
80
58
|
|
|
81
|
-
export const splitPath = (path?: string):
|
|
59
|
+
export const splitPath = (path?: string): PathPart[] => path === undefined ? [] : path.split("/").filter(p => p).map(p => {
|
|
82
60
|
return {
|
|
83
61
|
value: p,
|
|
84
62
|
lower: p.toLocaleLowerCase()
|
|
85
63
|
};
|
|
86
64
|
});
|
|
87
65
|
|
|
88
|
-
export
|
|
66
|
+
export function tokenizePath(path?: string): PathPartToken[] {
|
|
89
67
|
if (path === undefined) {
|
|
90
68
|
return [];
|
|
91
69
|
}
|
|
@@ -98,36 +76,36 @@ export const tokenizePath = (path?: string): PathPartToken[] => {
|
|
|
98
76
|
return tokens;
|
|
99
77
|
}
|
|
100
78
|
|
|
101
|
-
export
|
|
79
|
+
export function matchTokenizePath(checkAsRouter: boolean, pathTokens: PathPartToken[], requestParts: PathPart[]): {
|
|
102
80
|
match: boolean;
|
|
103
81
|
params?: { [name: string]: string | undefined }
|
|
104
|
-
}
|
|
105
|
-
for (let i = 0; i <
|
|
106
|
-
if (
|
|
82
|
+
} {
|
|
83
|
+
for (let i = 0; i < pathTokens.length; i++) {
|
|
84
|
+
if (pathTokens[i].optional && i != pathTokens.length - 1) {
|
|
107
85
|
throw new Error("cannot set a path token as optional that's not the last one");
|
|
108
86
|
}
|
|
109
87
|
}
|
|
110
|
-
const lastTokenIsOptional =
|
|
88
|
+
const lastTokenIsOptional = pathTokens.length > 0 ? pathTokens[pathTokens.length - 1].optional : false;
|
|
111
89
|
const couldBeUsingOptional = (lastTokenIsOptional &&
|
|
112
90
|
(
|
|
113
|
-
(!checkAsRouter &&
|
|
114
|
-
(checkAsRouter &&
|
|
91
|
+
(!checkAsRouter && pathTokens.length - 1 === requestParts.length) ||
|
|
92
|
+
(checkAsRouter && pathTokens.length - 1 <= requestParts.length)
|
|
115
93
|
)
|
|
116
94
|
);
|
|
117
95
|
|
|
118
|
-
const params: { [name: string]: string | undefined } =
|
|
96
|
+
const params: { [name: string]: string | undefined } = Object.create(null);
|
|
119
97
|
|
|
120
|
-
if ((!checkAsRouter &&
|
|
121
|
-
//
|
|
122
|
-
for (let i = 0; i <
|
|
123
|
-
const ctxToken =
|
|
124
|
-
if (checkAsRouter && i >=
|
|
98
|
+
if ((!checkAsRouter && pathTokens.length === requestParts.length) || couldBeUsingOptional || (checkAsRouter && pathTokens.length <= requestParts.length)) {
|
|
99
|
+
// similar count of tokens
|
|
100
|
+
for (let i = 0; i < requestParts.length; i++) {
|
|
101
|
+
const ctxToken = requestParts[i];
|
|
102
|
+
if (checkAsRouter && i >= pathTokens.length) {
|
|
125
103
|
break;
|
|
126
104
|
}
|
|
127
105
|
|
|
128
|
-
if (
|
|
106
|
+
if (pathTokens[i].wild || ctxToken.lower === pathTokens[i].lower) {
|
|
129
107
|
// check pass
|
|
130
|
-
const wild =
|
|
108
|
+
const wild = pathTokens[i].wild;
|
|
131
109
|
if (wild) {
|
|
132
110
|
params[wild] = ctxToken.value;
|
|
133
111
|
}
|
package/src/middleware/group.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {BadRequestError, Context, ForbiddenError, GroupPolicy, Handler, Session, UnAuthorizedError} from "../common";
|
|
2
|
+
import {parse} from "@miqro/parser";
|
|
2
3
|
|
|
3
4
|
const policyCheck = (session: Session, options: GroupPolicy): boolean => {
|
|
4
5
|
switch (options.groupPolicy) {
|
|
@@ -43,6 +44,7 @@ const policyCheck = (session: Session, options: GroupPolicy): boolean => {
|
|
|
43
44
|
};
|
|
44
45
|
|
|
45
46
|
export const GroupPolicyHandler = (options: GroupPolicy): Handler<void> => {
|
|
47
|
+
options = parse(options, "GroupPolicy", undefined, "options");
|
|
46
48
|
return function GroupPolicyHandler(ctx: Context): void {
|
|
47
49
|
try {
|
|
48
50
|
if (!ctx.session) {
|
package/src/middleware/index.ts
CHANGED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import {parse, ParseOptions, ParserInterface} from "@miqro/parser";
|
|
2
|
+
import {Context, Handler} from "../common/context";
|
|
3
|
+
|
|
4
|
+
export const ResultParser = (options: ParseOptions | ParseOptions[] | string, parser?: ParserInterface): Handler => {
|
|
5
|
+
options = parse(options, "ParseOptions[]!|string", undefined, "options");
|
|
6
|
+
return async function ResultParser(ctx: Context): Promise<any> {
|
|
7
|
+
if (!ctx.results || ctx.results.length === 0) {
|
|
8
|
+
ctx.logger.debug(`not parsing results`);
|
|
9
|
+
return undefined;
|
|
10
|
+
} else {
|
|
11
|
+
const index = ctx.results.length - 1;
|
|
12
|
+
const lastResult = ctx.results[index];
|
|
13
|
+
ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
|
|
14
|
+
try {
|
|
15
|
+
if (options instanceof Array) {
|
|
16
|
+
for (let i = 0; i < options.length; i++) {
|
|
17
|
+
const o = options[i];
|
|
18
|
+
try {
|
|
19
|
+
const mappedResults = (parser ? parser : {parse}).parse(lastResult, o.options, o.mode, `ctx.results[${index}]`);
|
|
20
|
+
ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
|
|
21
|
+
return mappedResults;
|
|
22
|
+
} catch (e) {
|
|
23
|
+
if (i === options.length - 1) {
|
|
24
|
+
throw e;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
} else if (typeof options !== "string") {
|
|
29
|
+
const mappedResults = (parser ? parser : {parse}).parse(lastResult, options.options, options.mode, `ctx.results[${index}]`);
|
|
30
|
+
ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
|
|
31
|
+
return mappedResults;
|
|
32
|
+
} else {
|
|
33
|
+
const mappedResults = (parser ? parser : {parse}).parse(lastResult, options, "no_extra", `ctx.results[${index}]`);
|
|
34
|
+
ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
|
|
35
|
+
return mappedResults;
|
|
36
|
+
}
|
|
37
|
+
} catch (e) {
|
|
38
|
+
ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
|
|
39
|
+
throw e;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
const {fake, requireMock} = require("@miqro/test");
|
|
2
|
+
const {resolve} = require("path");
|
|
3
|
+
const {strictEqual} = require("assert");
|
|
4
|
+
const {distPath, basePath} = require("./setup-test.js");
|
|
5
|
+
|
|
6
|
+
const testFilePath = resolve(distPath, "proxy.js");
|
|
7
|
+
|
|
8
|
+
describe("proxy unit tests", () => {
|
|
9
|
+
[{
|
|
10
|
+
fakeOptions: {
|
|
11
|
+
url: "http://localhost"
|
|
12
|
+
}
|
|
13
|
+
}, {
|
|
14
|
+
fakeOptions: {
|
|
15
|
+
url: "http://localhost",
|
|
16
|
+
rejectUnauthorized: true
|
|
17
|
+
}
|
|
18
|
+
}, {
|
|
19
|
+
fakeOptions: {
|
|
20
|
+
url: "http://localhost",
|
|
21
|
+
rejectUnauthorized: false
|
|
22
|
+
}
|
|
23
|
+
}].forEach(({fakeOptions}) => {
|
|
24
|
+
it("ctor with " + JSON.stringify(fakeOptions), async () => {
|
|
25
|
+
const routerCtr = fake(() => {
|
|
26
|
+
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const normalizePathRet = "normalizePathRet";
|
|
30
|
+
|
|
31
|
+
const urlCtr = fake(() => {
|
|
32
|
+
return "fakePath";
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
class Router {
|
|
36
|
+
constructor(options) {
|
|
37
|
+
routerCtr(options);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
class URL {
|
|
42
|
+
constructor(options) {
|
|
43
|
+
this.pathname = urlCtr(options);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const normalizePath = fake((args) => {
|
|
48
|
+
return normalizePathRet;
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const {Proxy} = requireMock(testFilePath, {
|
|
52
|
+
"./common": {},
|
|
53
|
+
"@miqro/request": {},
|
|
54
|
+
"./router": {
|
|
55
|
+
Router
|
|
56
|
+
},
|
|
57
|
+
"./common/tokenize-match": {
|
|
58
|
+
normalizePath
|
|
59
|
+
},
|
|
60
|
+
"url": {
|
|
61
|
+
URL
|
|
62
|
+
},
|
|
63
|
+
}, basePath);
|
|
64
|
+
// console.dir(Object.keys(require.cache));
|
|
65
|
+
const router = Proxy(fakeOptions);
|
|
66
|
+
strictEqual(router.proxyURL.pathname, normalizePathRet);
|
|
67
|
+
strictEqual(router.rejectUnauthorized, fakeOptions.rejectUnauthorized);
|
|
68
|
+
strictEqual(router.proxyURL instanceof URL, true);
|
|
69
|
+
strictEqual(routerCtr.callCount, 1);
|
|
70
|
+
strictEqual(routerCtr.callArgs[0][0], fakeOptions);
|
|
71
|
+
strictEqual(urlCtr.callCount, 1);
|
|
72
|
+
strictEqual(urlCtr.callArgs[0][0], fakeOptions.url);
|
|
73
|
+
strictEqual(normalizePath.callCount, 1);
|
|
74
|
+
strictEqual(normalizePath.callArgs[0][0], "fakePath");
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
[{
|
|
78
|
+
context: {
|
|
79
|
+
path: "/",
|
|
80
|
+
res: {
|
|
81
|
+
headersSent: false
|
|
82
|
+
},
|
|
83
|
+
logger: {
|
|
84
|
+
info: fake(() => {
|
|
85
|
+
|
|
86
|
+
})
|
|
87
|
+
},
|
|
88
|
+
end: fake(()=>{
|
|
89
|
+
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
}].forEach(({context}) => {
|
|
93
|
+
it("this.run: super.run returns true with options " + JSON.stringify(fakeOptions) + " and context " + context.path, async () => {
|
|
94
|
+
const routerCtr = fake(() => {
|
|
95
|
+
|
|
96
|
+
});
|
|
97
|
+
const routerRun = fake(async () => {
|
|
98
|
+
return true;
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const normalizePathRet = "normalizePathRet";
|
|
102
|
+
|
|
103
|
+
const urlCtr = fake(() => {
|
|
104
|
+
return "fakePath";
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
class Router {
|
|
108
|
+
constructor(options) {
|
|
109
|
+
routerCtr(options);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
run() {
|
|
113
|
+
return routerRun(...arguments);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
class URL {
|
|
118
|
+
constructor(options) {
|
|
119
|
+
this.pathname = urlCtr(options);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const normalizePath = fake((args) => {
|
|
124
|
+
return normalizePathRet;
|
|
125
|
+
});
|
|
126
|
+
const requestRet = {
|
|
127
|
+
|
|
128
|
+
};
|
|
129
|
+
const request = fake(async () => {
|
|
130
|
+
return requestRet;
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const {Proxy} = requireMock(testFilePath, {
|
|
134
|
+
"./common": {},
|
|
135
|
+
"@miqro/request": {
|
|
136
|
+
request
|
|
137
|
+
},
|
|
138
|
+
"./router": {
|
|
139
|
+
Router
|
|
140
|
+
},
|
|
141
|
+
"./common/tokenize-match": {
|
|
142
|
+
normalizePath
|
|
143
|
+
},
|
|
144
|
+
"url": {
|
|
145
|
+
URL
|
|
146
|
+
},
|
|
147
|
+
}, basePath);
|
|
148
|
+
//console.dir(Object.keys(require.cache))
|
|
149
|
+
const router = Proxy(fakeOptions);
|
|
150
|
+
const ret = await router.run(context);
|
|
151
|
+
strictEqual(request.callCount, 1);
|
|
152
|
+
// TODO assert path
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
});
|
package/src/router.ts
CHANGED
|
@@ -2,203 +2,11 @@ import {IncomingMessage, RequestListener} from "http";
|
|
|
2
2
|
import {v4} from "uuid";
|
|
3
3
|
import {Logger} from "./common/logger";
|
|
4
4
|
import {Context, ErrorHandler, Handler, Method} from "./common/context";
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
ResponseHandler,
|
|
8
|
-
ResultParser,
|
|
9
|
-
RouterHandlerOptions,
|
|
10
|
-
RouterJSONDoc
|
|
11
|
-
} from "./common/router-utils";
|
|
12
|
-
import {matchTokenizePath, normalizePath, PathPartToken, splitPath, tokenizePath} from "./common/tokenize-match";
|
|
5
|
+
import {HandlerWithOptions, RouterHandlerOptions, RouterJSONDoc} from "./common/router-utils";
|
|
6
|
+
import {normalizePath, PathPart, PathPartToken, splitPath} from "./common/tokenize-match";
|
|
13
7
|
import {defaultLoggerFactory} from "./common/router-helpers";
|
|
14
|
-
import {
|
|
15
|
-
import {parse, ParseOptionMap} from "@miqro/parser";
|
|
8
|
+
import {RouterHandler} from "./common/router-handler";
|
|
16
9
|
|
|
17
|
-
const ROUTE_OPTIONS: ParseOptionMap = {
|
|
18
|
-
name: "string?",
|
|
19
|
-
description: "string?",
|
|
20
|
-
policy: "GroupPolicy?",
|
|
21
|
-
response: {
|
|
22
|
-
type: "nested?",
|
|
23
|
-
nestedOptions: {
|
|
24
|
-
options: {
|
|
25
|
-
body: "boolean?|ParseOptions[]!?|string?"
|
|
26
|
-
},
|
|
27
|
-
mode: "no_extra"
|
|
28
|
-
}
|
|
29
|
-
},
|
|
30
|
-
request: {
|
|
31
|
-
type: "nested?",
|
|
32
|
-
nestedOptions: {
|
|
33
|
-
options: {
|
|
34
|
-
headers: "ParseOptions[]!?",
|
|
35
|
-
query: "boolean?|ParseOptions[]!?|string?",
|
|
36
|
-
params: "boolean?|ParseOptions[]!?|string?",
|
|
37
|
-
body: "boolean?|ParseOptions[]!?|string?"
|
|
38
|
-
},
|
|
39
|
-
mode: "no_extra"
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
class RouterHandler {
|
|
45
|
-
|
|
46
|
-
private readonly tokens: PathPartToken[];
|
|
47
|
-
private readonly handler: Array<Handler | Router>;
|
|
48
|
-
private readonly isRouter: boolean;
|
|
49
|
-
private readonly options?: RouterHandlerOptions;
|
|
50
|
-
|
|
51
|
-
public constructor(
|
|
52
|
-
handler: Array<Handler> | HandlerWithOptions | Handler | Router,
|
|
53
|
-
private readonly path: string | undefined,
|
|
54
|
-
private readonly method: Method | undefined,
|
|
55
|
-
options?: RouterHandlerOptions) {
|
|
56
|
-
this.tokens = tokenizePath(path);
|
|
57
|
-
|
|
58
|
-
if (options) {
|
|
59
|
-
options = parse(options, {
|
|
60
|
-
parser: "ParserInterface?",
|
|
61
|
-
middleware: "function[]!?",
|
|
62
|
-
session: "SessionHandlerOptions?|function?",
|
|
63
|
-
...ROUTE_OPTIONS
|
|
64
|
-
}, "no_extra", "options");
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
let handlers: Array<Handler | Router> = []
|
|
68
|
-
this.isRouter = handler instanceof Router;
|
|
69
|
-
|
|
70
|
-
if (!this.isRouter && !(handler instanceof Array) && typeof handler === "object") {
|
|
71
|
-
// HandlerWithOptions
|
|
72
|
-
if (options) {
|
|
73
|
-
throw new Error("bad arguments. cannot send options with HandlerWithOptions");
|
|
74
|
-
}
|
|
75
|
-
handler = parse(handler, {
|
|
76
|
-
handler: "function[]!",
|
|
77
|
-
parser: "ParserInterface?",
|
|
78
|
-
middleware: "function[]!?",
|
|
79
|
-
session: "SessionHandlerOptions?|function?",
|
|
80
|
-
...ROUTE_OPTIONS
|
|
81
|
-
}, "no_extra", "handler");
|
|
82
|
-
const realHandler = (handler as HandlerWithOptions).handler;
|
|
83
|
-
const newOptions = {
|
|
84
|
-
...(handler as HandlerWithOptions)
|
|
85
|
-
};
|
|
86
|
-
delete (newOptions as any).handler;
|
|
87
|
-
handler = realHandler;
|
|
88
|
-
this.options = newOptions;
|
|
89
|
-
} else {
|
|
90
|
-
this.options = options;
|
|
91
|
-
}
|
|
92
|
-
const routeHandlers = handler instanceof Array ? handler : [handler] as Array<Handler | Router>;
|
|
93
|
-
|
|
94
|
-
if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && this.options)) {
|
|
95
|
-
throw new Error("bad arguments");
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
if (this.options && this.options.middleware) {
|
|
99
|
-
handlers = handlers.concat(this.options.middleware);
|
|
100
|
-
}
|
|
101
|
-
if (this.options && this.options.session) {
|
|
102
|
-
handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
|
|
103
|
-
}
|
|
104
|
-
if (this.options && this.options.policy) {
|
|
105
|
-
handlers.push(GroupPolicyHandler(this.options.policy));
|
|
106
|
-
}
|
|
107
|
-
if (this.options && this.options.request) {
|
|
108
|
-
handlers.push(ParseRequest(this.options.request, this.options.parser));
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
handlers = handlers.concat(routeHandlers);
|
|
112
|
-
|
|
113
|
-
if (this.options && this.options.response) {
|
|
114
|
-
if (typeof this.options.response.body === "boolean" && this.options.response.body) {
|
|
115
|
-
(handlers as Handler[]).push(ResponseHandler());
|
|
116
|
-
} else if (this.options.response.body) {
|
|
117
|
-
(handlers as Handler[]).push(ResultParser(this.options.response.body, this.options.parser));
|
|
118
|
-
(handlers as Handler[]).push(ResponseHandler());
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
this.handler = handlers;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
|
|
125
|
-
const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
|
|
126
|
-
const nMethod = this.method ? this.method : "";
|
|
127
|
-
|
|
128
|
-
if (this.isRouter) {
|
|
129
|
-
const router: Router = this.handler[0] as Router;
|
|
130
|
-
router.getJSONDoc(doc, `${prePath}${nPath}`);
|
|
131
|
-
} else if (this.options) {
|
|
132
|
-
if (!doc[`${prePath}${nPath}`]) {
|
|
133
|
-
doc[`${prePath}${nPath}`] = {};
|
|
134
|
-
}
|
|
135
|
-
if (doc[`${prePath}${nPath}`][nMethod]) {
|
|
136
|
-
throw new Error("cannot create doc routes override each other");
|
|
137
|
-
}
|
|
138
|
-
doc[`${prePath}${nPath}`][nMethod] = {
|
|
139
|
-
description: this.options.description,
|
|
140
|
-
name: this.options.name,
|
|
141
|
-
identifier: `${prePath}${nPath}${this.options.name ? this.options.name : ""}${nMethod ? `_${nMethod}` : ""}`.replace(/[^a-z0-9+]+/gi, '_').split("_").map(s => s.trim()).filter(s => s).join("_").toUpperCase(),
|
|
142
|
-
policy: this.options.policy,
|
|
143
|
-
request: this.options.request ? {
|
|
144
|
-
body: this.options.request.body,
|
|
145
|
-
headers: this.options.request.headers,
|
|
146
|
-
params: this.options.request.params,
|
|
147
|
-
query: this.options.request.query,
|
|
148
|
-
} : undefined,
|
|
149
|
-
response: this.options.response
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
return doc;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
|
|
156
|
-
for (let i = 0; i < this.handler.length; i++) {
|
|
157
|
-
const h = this.handler[i];
|
|
158
|
-
if (h instanceof Router) {
|
|
159
|
-
if (!RouterHandler.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
|
|
160
|
-
return false;
|
|
161
|
-
}
|
|
162
|
-
} else {
|
|
163
|
-
if (!RouterHandler.pushResults(await h(ctx), ctx)) {
|
|
164
|
-
return false;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
return true;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
public isMatch(
|
|
172
|
-
method: string,
|
|
173
|
-
pathTokens: { value: string; lower: string; }[],
|
|
174
|
-
prePathTokens: PathPartToken[]): {
|
|
175
|
-
match: boolean;
|
|
176
|
-
params?: { [name: string]: string | undefined }
|
|
177
|
-
} {
|
|
178
|
-
if ((this.method === undefined || this.method === method)) {
|
|
179
|
-
if (this.path === undefined) {
|
|
180
|
-
return {
|
|
181
|
-
match: true
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
|
|
185
|
-
}
|
|
186
|
-
return {
|
|
187
|
-
match: false
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
private static pushResults(result: any, ctx: Context): boolean {
|
|
192
|
-
if (result === false) {
|
|
193
|
-
// ctx.logger.debug(`avoiding next handlers because handler returned false.`);
|
|
194
|
-
return false;
|
|
195
|
-
} else if (result !== true && result !== undefined) {
|
|
196
|
-
ctx.logger.trace("pushing to results [%o]", result);
|
|
197
|
-
ctx.results.push(result);
|
|
198
|
-
}
|
|
199
|
-
return true;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
10
|
|
|
203
11
|
export interface RouterOptions {
|
|
204
12
|
loggerFactory?: (uuid: string, req: IncomingMessage) => Logger;
|
|
@@ -254,12 +62,15 @@ export class Router {
|
|
|
254
62
|
public catch(errorHandler: Array<ErrorHandler> | ErrorHandler): Router {
|
|
255
63
|
const errorHandlers = errorHandler instanceof Array ? errorHandler : [errorHandler];
|
|
256
64
|
for (const e of errorHandlers) {
|
|
65
|
+
if (typeof e !== "function") {
|
|
66
|
+
throw new Error(`errorHandler ${e} not a function!`);
|
|
67
|
+
}
|
|
257
68
|
this.errorHandlers.push(e);
|
|
258
69
|
}
|
|
259
70
|
return this;
|
|
260
71
|
}
|
|
261
72
|
|
|
262
|
-
public async run(ctx: Context, pathTokens?:
|
|
73
|
+
public async run(ctx: Context, pathTokens?: PathPart[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
|
|
263
74
|
pathTokens = pathTokens ? pathTokens : splitPath(ctx.path);
|
|
264
75
|
try {
|
|
265
76
|
for (const h of this.handlers) {
|