@miqro/core 4.0.1 → 5.0.3
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/build/app.d.ts +15 -11
- package/build/app.js +22 -20
- package/build/app.js.map +1 -1
- package/build/common.d.ts +106 -0
- package/build/common.js +477 -0
- package/build/common.js.map +1 -0
- package/build/lib.d.ts +7 -38
- package/build/lib.js +6 -33
- package/build/lib.js.map +1 -1
- package/build/middleware/body-parser.d.ts +78 -0
- package/build/middleware/body-parser.js +548 -0
- package/build/middleware/body-parser.js.map +1 -0
- package/build/middleware/router.d.ts +114 -0
- package/build/middleware/router.js +704 -0
- package/build/middleware/router.js.map +1 -0
- package/build/middleware/session.d.ts +27 -3
- package/build/middleware/session.js +238 -18
- package/build/middleware/session.js.map +1 -1
- package/build/types.d.ts +309 -0
- package/build/types.js +455 -0
- package/build/types.js.map +1 -0
- package/build/{websocket/cluster.d.ts → websocket.d.ts} +13 -2
- package/build/websocket.js +316 -0
- package/build/websocket.js.map +1 -0
- package/package.json +7 -7
- package/src/app.ts +36 -32
- package/src/common.ts +528 -0
- package/src/lib.ts +63 -101
- package/src/middleware/body-parser.ts +593 -0
- package/src/middleware/router.ts +840 -0
- package/src/middleware/session.ts +249 -19
- package/src/types.ts +785 -0
- package/src/websocket.ts +356 -0
- package/build/api-router.d.ts +0 -34
- package/build/api-router.js +0 -48
- package/build/api-router.js.map +0 -1
- package/build/app-utils.d.ts +0 -13
- package/build/app-utils.js +0 -78
- package/build/app-utils.js.map +0 -1
- package/build/common/api-router-types.d.ts +0 -28
- package/build/common/api-router-types.js +0 -24
- package/build/common/api-router-types.js.map +0 -1
- package/build/common/api-router-utils.d.ts +0 -3
- package/build/common/api-router-utils.js +0 -118
- package/build/common/api-router-utils.js.map +0 -1
- package/build/common/config/config.d.ts +0 -15
- package/build/common/config/config.js +0 -38
- package/build/common/config/config.js.map +0 -1
- package/build/common/config/featuretoggle.d.ts +0 -1
- package/build/common/config/featuretoggle.js +0 -6
- package/build/common/config/featuretoggle.js.map +0 -1
- package/build/common/config/loader.d.ts +0 -13
- package/build/common/config/loader.js +0 -64
- package/build/common/config/loader.js.map +0 -1
- package/build/common/context.d.ts +0 -57
- package/build/common/context.js +0 -137
- package/build/common/context.js.map +0 -1
- package/build/common/error/badrequesterror.d.ts +0 -3
- package/build/common/error/badrequesterror.js +0 -7
- package/build/common/error/badrequesterror.js.map +0 -1
- package/build/common/error/configfilenotfound.d.ts +0 -3
- package/build/common/error/configfilenotfound.js +0 -7
- package/build/common/error/configfilenotfound.js.map +0 -1
- package/build/common/error/forbiddenerror.d.ts +0 -3
- package/build/common/error/forbiddenerror.js +0 -7
- package/build/common/error/forbiddenerror.js.map +0 -1
- package/build/common/error/notfound.d.ts +0 -3
- package/build/common/error/notfound.js +0 -7
- package/build/common/error/notfound.js.map +0 -1
- package/build/common/error/notimplemented.d.ts +0 -3
- package/build/common/error/notimplemented.js +0 -7
- package/build/common/error/notimplemented.js.map +0 -1
- package/build/common/error/unauthorizederror.d.ts +0 -3
- package/build/common/error/unauthorizederror.js +0 -7
- package/build/common/error/unauthorizederror.js.map +0 -1
- package/build/common/logger/constants.d.ts +0 -14
- package/build/common/logger/constants.js +0 -22
- package/build/common/logger/constants.js.map +0 -1
- package/build/common/logger/factory.d.ts +0 -16
- package/build/common/logger/factory.js +0 -47
- package/build/common/logger/factory.js.map +0 -1
- package/build/common/logger/interfaces.d.ts +0 -18
- package/build/common/logger/interfaces.js +0 -2
- package/build/common/logger/interfaces.js.map +0 -1
- package/build/common/logger/logger.d.ts +0 -35
- package/build/common/logger/logger.js +0 -95
- package/build/common/logger/logger.js.map +0 -1
- package/build/common/logger/transport/console.d.ts +0 -5
- package/build/common/logger/transport/console.js +0 -37
- package/build/common/logger/transport/console.js.map +0 -1
- package/build/common/logger/transport/file.d.ts +0 -2
- package/build/common/logger/transport/file.js +0 -25
- package/build/common/logger/transport/file.js.map +0 -1
- package/build/common/parser.d.ts +0 -7
- package/build/common/parser.js +0 -44
- package/build/common/parser.js.map +0 -1
- package/build/common/router-default-logger-factory.d.ts +0 -4
- package/build/common/router-default-logger-factory.js +0 -38
- package/build/common/router-default-logger-factory.js.map +0 -1
- package/build/common/router-handler.d.ts +0 -20
- package/build/common/router-handler.js +0 -154
- package/build/common/router-handler.js.map +0 -1
- package/build/common/router-types.d.ts +0 -63
- package/build/common/router-types.js +0 -86
- package/build/common/router-types.js.map +0 -1
- package/build/common/router-utils.d.ts +0 -3
- package/build/common/router-utils.js +0 -46
- package/build/common/router-utils.js.map +0 -1
- package/build/common/session/common.d.ts +0 -37
- package/build/common/session/common.js +0 -2
- package/build/common/session/common.js.map +0 -1
- package/build/common/session/service.d.ts +0 -26
- package/build/common/session/service.js +0 -154
- package/build/common/session/service.js.map +0 -1
- package/build/common/tokenize-match.d.ts +0 -19
- package/build/common/tokenize-match.js +0 -73
- package/build/common/tokenize-match.js.map +0 -1
- package/build/common/url-utils.d.ts +0 -6
- package/build/common/url-utils.js +0 -48
- package/build/common/url-utils.js.map +0 -1
- package/build/middleware/buffer.d.ts +0 -6
- package/build/middleware/buffer.js +0 -78
- package/build/middleware/buffer.js.map +0 -1
- package/build/middleware/cookie.d.ts +0 -4
- package/build/middleware/cookie.js +0 -15
- package/build/middleware/cookie.js.map +0 -1
- package/build/middleware/cors.d.ts +0 -8
- package/build/middleware/cors.js +0 -89
- package/build/middleware/cors.js.map +0 -1
- package/build/middleware/form.d.ts +0 -6
- package/build/middleware/form.js +0 -58
- package/build/middleware/form.js.map +0 -1
- package/build/middleware/group.d.ts +0 -3
- package/build/middleware/group.js +0 -77
- package/build/middleware/group.js.map +0 -1
- package/build/middleware/json.d.ts +0 -6
- package/build/middleware/json.js +0 -55
- package/build/middleware/json.js.map +0 -1
- package/build/middleware/logger.d.ts +0 -4
- package/build/middleware/logger.js +0 -16
- package/build/middleware/logger.js.map +0 -1
- package/build/middleware/parse.d.ts +0 -14
- package/build/middleware/parse.js +0 -88
- package/build/middleware/parse.js.map +0 -1
- package/build/middleware/result.d.ts +0 -9
- package/build/middleware/result.js +0 -62
- package/build/middleware/result.js.map +0 -1
- package/build/middleware/tag.d.ts +0 -4
- package/build/middleware/tag.js +0 -10
- package/build/middleware/tag.js.map +0 -1
- package/build/middleware/text.d.ts +0 -5
- package/build/middleware/text.js +0 -46
- package/build/middleware/text.js.map +0 -1
- package/build/proxy.d.ts +0 -19
- package/build/proxy.js +0 -74
- package/build/proxy.js.map +0 -1
- package/build/router.d.ts +0 -26
- package/build/router.js +0 -116
- package/build/router.js.map +0 -1
- package/build/static.d.ts +0 -14
- package/build/static.js +0 -211
- package/build/static.js.map +0 -1
- package/build/websocket/cluster.js +0 -114
- package/build/websocket/cluster.js.map +0 -1
- package/build/websocket/server.d.ts +0 -15
- package/build/websocket/server.js +0 -127
- package/build/websocket/server.js.map +0 -1
- package/build/websocket/types.d.ts +0 -39
- package/build/websocket/types.js +0 -2
- package/build/websocket/types.js.map +0 -1
- package/build/websocket/utils.d.ts +0 -8
- package/build/websocket/utils.js +0 -77
- package/build/websocket/utils.js.map +0 -1
- package/src/api-router.ts +0 -50
- package/src/app-utils.ts +0 -82
- package/src/common/api-router-types.ts +0 -52
- package/src/common/api-router-utils.ts +0 -126
- package/src/common/config/config.ts +0 -49
- package/src/common/config/featuretoggle.ts +0 -6
- package/src/common/config/loader.ts +0 -81
- package/src/common/context.ts +0 -192
- package/src/common/error/badrequesterror.ts +0 -6
- package/src/common/error/configfilenotfound.ts +0 -6
- package/src/common/error/forbiddenerror.ts +0 -6
- package/src/common/error/notfound.ts +0 -6
- package/src/common/error/notimplemented.ts +0 -6
- package/src/common/error/unauthorizederror.ts +0 -6
- package/src/common/logger/constants.ts +0 -28
- package/src/common/logger/factory.ts +0 -53
- package/src/common/logger/interfaces.ts +0 -19
- package/src/common/logger/logger.ts +0 -136
- package/src/common/logger/transport/console.ts +0 -36
- package/src/common/logger/transport/file.ts +0 -26
- package/src/common/parser.ts +0 -50
- package/src/common/router-default-logger-factory.ts +0 -44
- package/src/common/router-handler.ts +0 -186
- package/src/common/router-types.ts +0 -153
- package/src/common/router-utils.ts +0 -47
- package/src/common/session/common.ts +0 -40
- package/src/common/session/service.ts +0 -175
- package/src/common/tokenize-match.ts +0 -98
- package/src/common/url-utils.ts +0 -46
- package/src/middleware/buffer.ts +0 -82
- package/src/middleware/cookie.ts +0 -20
- package/src/middleware/cors.ts +0 -98
- package/src/middleware/form.ts +0 -61
- package/src/middleware/group.ts +0 -74
- package/src/middleware/json.ts +0 -57
- package/src/middleware/logger.ts +0 -18
- package/src/middleware/parse.ts +0 -105
- package/src/middleware/result.ts +0 -73
- package/src/middleware/tag.ts +0 -15
- package/src/middleware/text.ts +0 -47
- package/src/proxy.ts +0 -99
- package/src/router.ts +0 -140
- package/src/static.ts +0 -242
- package/src/websocket/cluster.ts +0 -128
- package/src/websocket/server.ts +0 -135
- package/src/websocket/types.ts +0 -41
- package/src/websocket/utils.ts +0 -95
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
import { routerDefaultLoggerFactory } from "../common.js";
|
|
2
|
+
import { Request, Response, HandlerWithOptionsSchema, RouterHandlerOptionsSchema, isMinimalRouter, normalizePath, matchTokenizePath, splitPath, tokenizePath, APIRouterOptionsSchema, APIRouteSchema, } from "../types.js";
|
|
3
|
+
import { SessionHandler, GroupPolicyHandler } from "./session.js";
|
|
4
|
+
import { DEFAULT_PARSER, assertNotUndefined, ResponseHandler, ResultParser, ParseRequest } from "./body-parser.js";
|
|
5
|
+
import { request } from "@miqro/request";
|
|
6
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "fs";
|
|
7
|
+
import { basename, extname, join, parse, resolve } from "path";
|
|
8
|
+
/**
|
|
9
|
+
* Router Public
|
|
10
|
+
*/
|
|
11
|
+
export class Router {
|
|
12
|
+
constructor(config) {
|
|
13
|
+
this.config = config;
|
|
14
|
+
this.handlers = [];
|
|
15
|
+
this.errorHandlers = [];
|
|
16
|
+
this.serverOptions = {
|
|
17
|
+
IncomingMessage: Request,
|
|
18
|
+
ServerResponse: Response
|
|
19
|
+
};
|
|
20
|
+
const loggerFactory = this.config && this.config.loggerFactory ? this.config.loggerFactory : routerDefaultLoggerFactory;
|
|
21
|
+
this.listener = async (req, res) => {
|
|
22
|
+
req.logger = loggerFactory(req.uuid, req);
|
|
23
|
+
req.logger.trace(`request received`);
|
|
24
|
+
await this.run(req, res);
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
get(path, handler, options) {
|
|
28
|
+
return this.use(handler, path, "get", options);
|
|
29
|
+
}
|
|
30
|
+
post(path, handler, options) {
|
|
31
|
+
return this.use(handler, path, "post", options);
|
|
32
|
+
}
|
|
33
|
+
patch(path, handler, options) {
|
|
34
|
+
return this.use(handler, path, "patch", options);
|
|
35
|
+
}
|
|
36
|
+
delete(path, handler, options) {
|
|
37
|
+
return this.use(handler, path, "delete", options);
|
|
38
|
+
}
|
|
39
|
+
put(path, handler, options) {
|
|
40
|
+
return this.use(handler, path, "put", options);
|
|
41
|
+
}
|
|
42
|
+
options(path, handler, options) {
|
|
43
|
+
return this.use(handler, path, "options", options);
|
|
44
|
+
}
|
|
45
|
+
use(handler, path, method, options) {
|
|
46
|
+
const nPath = path !== undefined ? normalizePath(path) : undefined;
|
|
47
|
+
const nMethod = method ? method.toLowerCase() : method;
|
|
48
|
+
this.handlers.push(new RouterHandler(handler, nPath, nMethod, options));
|
|
49
|
+
return this;
|
|
50
|
+
}
|
|
51
|
+
catch(errorHandler) {
|
|
52
|
+
const errorHandlers = errorHandler instanceof Array ? errorHandler : [errorHandler];
|
|
53
|
+
for (const e of errorHandlers) {
|
|
54
|
+
if (typeof e !== "function") {
|
|
55
|
+
throw new Error(`errorHandler ${e} not a function!`);
|
|
56
|
+
}
|
|
57
|
+
this.errorHandlers.push(e);
|
|
58
|
+
}
|
|
59
|
+
return this;
|
|
60
|
+
}
|
|
61
|
+
async run(req, res, pathTokens, prePathTokens = []) {
|
|
62
|
+
//console.log("run(%s, %o)", req.path, pathTokens);
|
|
63
|
+
pathTokens = pathTokens ? pathTokens : splitPath(req.path);
|
|
64
|
+
//console.log("run(%s, %o)", req.path, pathTokens);
|
|
65
|
+
try {
|
|
66
|
+
for (const h of this.handlers) {
|
|
67
|
+
if (res.headersSent) {
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
const isMatch = h.isMatch(req.method, pathTokens, prePathTokens);
|
|
71
|
+
//console.log("h.isMatch(%s, %o, %o)=%s", h.path, pathTokens, prePathTokens, isMatch);
|
|
72
|
+
if (isMatch.match) {
|
|
73
|
+
if (isMatch.params) {
|
|
74
|
+
req.params = req.params ? {
|
|
75
|
+
...req.params,
|
|
76
|
+
...isMatch.params
|
|
77
|
+
} : isMatch.params;
|
|
78
|
+
}
|
|
79
|
+
const shouldContinue = await h.invoke(req, res, pathTokens, prePathTokens);
|
|
80
|
+
if (!shouldContinue) {
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return !res.headersSent;
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
for (const eH of this.errorHandlers) {
|
|
89
|
+
const ret = await eH(e, req, res);
|
|
90
|
+
if (ret === false || res.headersSent) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
throw e; // pass the error along
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
getJSONDoc(doc = {}, prePath = "/") {
|
|
98
|
+
for (const h of this.handlers) {
|
|
99
|
+
doc = h.getJSONDoc(doc, prePath);
|
|
100
|
+
}
|
|
101
|
+
return doc;
|
|
102
|
+
}
|
|
103
|
+
logPaths(logger) {
|
|
104
|
+
this.toString().split("\n").forEach(l => logger.info(l));
|
|
105
|
+
}
|
|
106
|
+
toString() {
|
|
107
|
+
let ret = "";
|
|
108
|
+
const doc = this.getJSONDoc();
|
|
109
|
+
const paths = Object.keys(doc);
|
|
110
|
+
for (const path of paths) {
|
|
111
|
+
if (path) {
|
|
112
|
+
const pathData = doc[path];
|
|
113
|
+
const methods = Object.keys(pathData);
|
|
114
|
+
for (const method of methods) {
|
|
115
|
+
if (method) {
|
|
116
|
+
const methodData = pathData[method];
|
|
117
|
+
ret += `${ret === "" ? "" : "\n"}${method}:${path}\n\t${methodData.identifier}${methodData.name ? `\n\t\t${methodData.name}` : ""}${methodData.description ? `\n\t\t${methodData.description}` : ""}`;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return ret;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
class RouterHandler {
|
|
126
|
+
constructor(originalHandler, path, method, options) {
|
|
127
|
+
this.originalHandler = originalHandler;
|
|
128
|
+
this.path = path;
|
|
129
|
+
this.method = method;
|
|
130
|
+
this.tokens = tokenizePath(path);
|
|
131
|
+
if (options) {
|
|
132
|
+
options = assertNotUndefined(DEFAULT_PARSER.parse(options, RouterHandlerOptionsSchema, "options"), "bad options");
|
|
133
|
+
}
|
|
134
|
+
let handlers = [];
|
|
135
|
+
this.isRouter = isMinimalRouter(originalHandler); //handler instanceof Router;
|
|
136
|
+
if (!this.isRouter && !(originalHandler instanceof Array) && typeof originalHandler === "object") {
|
|
137
|
+
// HandlerWithOptions
|
|
138
|
+
if (options) {
|
|
139
|
+
throw new Error("bad arguments. cannot send options with HandlerWithOptions");
|
|
140
|
+
}
|
|
141
|
+
//console.dir(handler);
|
|
142
|
+
const handlerWithOptions = assertNotUndefined(DEFAULT_PARSER.parse(originalHandler, HandlerWithOptionsSchema, "handler"), "bad options");
|
|
143
|
+
this.originalHandler = handlerWithOptions.handler;
|
|
144
|
+
this.options = handlerWithOptions;
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
this.options = options;
|
|
148
|
+
}
|
|
149
|
+
const routeHandlers = this.originalHandler instanceof Array ? this.originalHandler : [this.originalHandler];
|
|
150
|
+
//if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && this.options)) {
|
|
151
|
+
if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length)) {
|
|
152
|
+
throw new Error(`bad arguments isRouter[${this.isRouter}]`);
|
|
153
|
+
}
|
|
154
|
+
if (this.options && this.options.middleware) {
|
|
155
|
+
handlers = handlers.concat(this.options.middleware);
|
|
156
|
+
}
|
|
157
|
+
if (this.options && this.options.session) {
|
|
158
|
+
handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
|
|
159
|
+
}
|
|
160
|
+
if (this.options && this.options.policy) {
|
|
161
|
+
handlers.push(GroupPolicyHandler(this.options.policy));
|
|
162
|
+
}
|
|
163
|
+
if (this.options && this.options.request) {
|
|
164
|
+
handlers.push(ParseRequest(this.options.request, this.options.parser));
|
|
165
|
+
}
|
|
166
|
+
handlers = handlers.concat(routeHandlers);
|
|
167
|
+
if (this.options && this.options.response && !this.isRouter) {
|
|
168
|
+
const responseMiddleware = typeof this.options.response === "boolean" ? [ResponseHandler] : this.options.response.middleware ? (this.options.response.middleware instanceof Array ?
|
|
169
|
+
this.options.response.middleware :
|
|
170
|
+
[this.options.response.middleware]) :
|
|
171
|
+
[ResponseHandler];
|
|
172
|
+
if (typeof this.options.response !== "boolean") {
|
|
173
|
+
handlers.push(ResultParser(this.options.response, this.options.parser));
|
|
174
|
+
}
|
|
175
|
+
handlers = handlers.concat(responseMiddleware);
|
|
176
|
+
}
|
|
177
|
+
this.handler = handlers;
|
|
178
|
+
}
|
|
179
|
+
getJSONDoc(doc = {}, prePath = "/") {
|
|
180
|
+
const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
|
|
181
|
+
const nMethod = this.method ? this.method : "";
|
|
182
|
+
if (this.isRouter) {
|
|
183
|
+
const router = this.originalHandler;
|
|
184
|
+
router.getJSONDoc(doc, `${prePath}${nPath}`);
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
if (!doc[`${prePath}${nPath}`]) {
|
|
188
|
+
doc[`${prePath}${nPath}`] = Object.create(null);
|
|
189
|
+
}
|
|
190
|
+
if (doc[`${prePath}${nPath}`][nMethod]) {
|
|
191
|
+
throw new Error("cannot create doc routes override each other");
|
|
192
|
+
}
|
|
193
|
+
if (this.options) {
|
|
194
|
+
doc[`${prePath}${nPath}`][nMethod] = {
|
|
195
|
+
description: this.options.description,
|
|
196
|
+
name: this.options.name,
|
|
197
|
+
identifier: this.options.identifier ? this.options.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(),
|
|
198
|
+
policy: this.options.policy,
|
|
199
|
+
request: this.options.request ? {
|
|
200
|
+
body: this.options.request.body,
|
|
201
|
+
headers: this.options.request.headers,
|
|
202
|
+
params: this.options.request.params,
|
|
203
|
+
query: this.options.request.query,
|
|
204
|
+
} : undefined,
|
|
205
|
+
response: typeof this.options.response === "boolean" ? this.options.response : this.options.response ? {
|
|
206
|
+
body: this.options.response.body
|
|
207
|
+
} : undefined
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
doc[`${prePath}${nPath}`][nMethod] = {
|
|
212
|
+
description: undefined,
|
|
213
|
+
name: undefined,
|
|
214
|
+
identifier: `${prePath}${nPath}${nMethod ? `_${nMethod}` : ""}`.replace(/[^a-z0-9+]+/gi, '_').split("_").map(s => s.trim()).filter(s => s).join("_").toUpperCase(),
|
|
215
|
+
policy: undefined,
|
|
216
|
+
request: undefined,
|
|
217
|
+
response: undefined
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return doc;
|
|
222
|
+
}
|
|
223
|
+
async invoke(req, res, pathTokens, prePathTokens) {
|
|
224
|
+
for (let i = 0; i < this.handler.length; i++) {
|
|
225
|
+
const h = this.handler[i];
|
|
226
|
+
if (isMinimalRouter(h)) {
|
|
227
|
+
//if (h instanceof Router) {
|
|
228
|
+
if (!RouterHandler.pushResults(await h.run(req, res, pathTokens, prePathTokens.concat(this.tokens)), req)) {
|
|
229
|
+
return false;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
if (!RouterHandler.pushResults(await h(req, res), req)) {
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
isMatch(method, requestParts, prePathTokens) {
|
|
241
|
+
if ((this.method === undefined || this.method === method)) {
|
|
242
|
+
if (this.path === undefined) {
|
|
243
|
+
//console.log("isMatch(%s, %s, %s)=%s", method, this.method, this.path, true);
|
|
244
|
+
return {
|
|
245
|
+
match: true
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
const ret = matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), requestParts);
|
|
249
|
+
//console.log("isMatch(%s, %s, %s)=%s", method, this.method, this.path, ret);
|
|
250
|
+
return ret;
|
|
251
|
+
}
|
|
252
|
+
//console.log("isMatch(%s, %s, %s)=%s", method, this.method, this.path, false);
|
|
253
|
+
return {
|
|
254
|
+
match: false
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
static pushResults(result, req) {
|
|
258
|
+
if (result === false) {
|
|
259
|
+
// ctx.logger.debug(`avoiding next handlers because handler returned false.`);
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
else if (result !== true && result !== undefined) {
|
|
263
|
+
req.logger.trace("pushing to results [%o]", result);
|
|
264
|
+
req.results.push(result);
|
|
265
|
+
}
|
|
266
|
+
return true;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
class ProxyRouter extends Router {
|
|
270
|
+
constructor(options) {
|
|
271
|
+
super(options);
|
|
272
|
+
const proxyURL = new URL(options.url);
|
|
273
|
+
proxyURL.pathname = normalizePath(proxyURL.pathname);
|
|
274
|
+
this.proxyURL = proxyURL;
|
|
275
|
+
this.rejectUnauthorized = options.rejectUnauthorized;
|
|
276
|
+
}
|
|
277
|
+
async run(req, res, pathTokens, prePathTokens = []) {
|
|
278
|
+
const level = prePathTokens.length;
|
|
279
|
+
const shouldContinue = await super.run(req, res, pathTokens, prePathTokens);
|
|
280
|
+
if (shouldContinue) {
|
|
281
|
+
const relative = req.path.split("/").map(s => s.trim()).filter(s => s).slice(level).join("/");
|
|
282
|
+
const nUrl = new URL(this.proxyURL.toString());
|
|
283
|
+
nUrl.pathname = nUrl.pathname + relative;
|
|
284
|
+
const url = nUrl.toString();
|
|
285
|
+
const headers = {
|
|
286
|
+
...req.headers
|
|
287
|
+
};
|
|
288
|
+
delete headers["connection"];
|
|
289
|
+
delete headers["keep-alive"];
|
|
290
|
+
let responseHeaders;
|
|
291
|
+
const requestArgs = {
|
|
292
|
+
url: url.toString(),
|
|
293
|
+
query: req.query,
|
|
294
|
+
disableThrow: true,
|
|
295
|
+
rejectUnauthorized: this.rejectUnauthorized,
|
|
296
|
+
disableUserAgent: true,
|
|
297
|
+
method: req.method,
|
|
298
|
+
headers,
|
|
299
|
+
onChunk: async function (chunk, chunkReq) {
|
|
300
|
+
const responseHeaders = {
|
|
301
|
+
...chunkReq.headers
|
|
302
|
+
};
|
|
303
|
+
delete responseHeaders["connection"];
|
|
304
|
+
delete responseHeaders["keep-alive"];
|
|
305
|
+
if (!res.headersSent) {
|
|
306
|
+
const headerNames = Object.keys(responseHeaders);
|
|
307
|
+
for (const name of headerNames) {
|
|
308
|
+
res.setHeader(name, responseHeaders[name]);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (chunkReq.statusCode !== undefined) {
|
|
312
|
+
res.statusCode = chunkReq.statusCode;
|
|
313
|
+
}
|
|
314
|
+
await res.asyncWrite(chunk);
|
|
315
|
+
},
|
|
316
|
+
data: req.method !== "GET" ? req.buffer : undefined
|
|
317
|
+
};
|
|
318
|
+
req.logger.info("proxy to %s", url.toString());
|
|
319
|
+
req.logger.debug("proxy with %o", requestArgs);
|
|
320
|
+
const response = await request(requestArgs);
|
|
321
|
+
if (!res.headersSent) {
|
|
322
|
+
const responseHeaders = {
|
|
323
|
+
...response.headers
|
|
324
|
+
};
|
|
325
|
+
const headerNames = Object.keys(responseHeaders);
|
|
326
|
+
for (const name of headerNames) {
|
|
327
|
+
res.setHeader(name, responseHeaders[name]);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
await res.end();
|
|
331
|
+
}
|
|
332
|
+
return !res.headersSent;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
export function Proxy(options) {
|
|
336
|
+
return new ProxyRouter(options);
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Static Router
|
|
340
|
+
*/
|
|
341
|
+
async function outputFile(path, contentType, req, res, allowGetJSON, status = 200) {
|
|
342
|
+
const buffer = readFileSync(path);
|
|
343
|
+
return allowGetJSON && req.query.format && req.query.format === "json" ?
|
|
344
|
+
res.json({
|
|
345
|
+
buffer
|
|
346
|
+
}) :
|
|
347
|
+
res.asyncEnd({
|
|
348
|
+
status,
|
|
349
|
+
headers: {
|
|
350
|
+
["Content-Type"]: contentType
|
|
351
|
+
},
|
|
352
|
+
body: buffer
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
async function generateList(path, req, res, allowListJSON) {
|
|
356
|
+
const files = readdirSync(path);
|
|
357
|
+
return allowListJSON && req.query.format && req.query.format === "json" ?
|
|
358
|
+
res.json({ files: files.map(f => `${req.path}${f}`) }) :
|
|
359
|
+
res.html(`<html><body><ul>${files.map(f => `<li><a href="${req.path}${f}">${f}</a></li>`).join("")}</ul></body></html>`);
|
|
360
|
+
}
|
|
361
|
+
export function Static(options) {
|
|
362
|
+
return new StaticRouter(options);
|
|
363
|
+
}
|
|
364
|
+
class StaticRouter extends Router {
|
|
365
|
+
constructor(options) {
|
|
366
|
+
super(options);
|
|
367
|
+
this.staticOptions = assertNotUndefined(DEFAULT_PARSER.parse(options, {
|
|
368
|
+
type: "object",
|
|
369
|
+
properties: {
|
|
370
|
+
loggerFactory: {
|
|
371
|
+
required: false,
|
|
372
|
+
type: "any"
|
|
373
|
+
},
|
|
374
|
+
directory: {
|
|
375
|
+
type: "string",
|
|
376
|
+
required: true
|
|
377
|
+
},
|
|
378
|
+
list: {
|
|
379
|
+
type: "boolean",
|
|
380
|
+
required: false,
|
|
381
|
+
defaultValue: false
|
|
382
|
+
},
|
|
383
|
+
allowListJSON: {
|
|
384
|
+
type: "boolean",
|
|
385
|
+
required: false,
|
|
386
|
+
defaultValue: false
|
|
387
|
+
},
|
|
388
|
+
allowGetJSON: {
|
|
389
|
+
type: "boolean",
|
|
390
|
+
required: false,
|
|
391
|
+
defaultValue: false
|
|
392
|
+
},
|
|
393
|
+
index: {
|
|
394
|
+
type: "string",
|
|
395
|
+
required: false,
|
|
396
|
+
defaultValue: "index.html"
|
|
397
|
+
},
|
|
398
|
+
index404: {
|
|
399
|
+
type: "string",
|
|
400
|
+
required: false
|
|
401
|
+
},
|
|
402
|
+
index404Status: {
|
|
403
|
+
type: "number",
|
|
404
|
+
required: false,
|
|
405
|
+
defaultValue: 404
|
|
406
|
+
},
|
|
407
|
+
contentTypes: {
|
|
408
|
+
type: "object",
|
|
409
|
+
required: false,
|
|
410
|
+
defaultValue: {
|
|
411
|
+
".aac": "audio/aac",
|
|
412
|
+
".abw": "application/x-abiword",
|
|
413
|
+
".arc": "application/x-freearc",
|
|
414
|
+
".avif": "image/avif",
|
|
415
|
+
".avi": "video/x-msvideo",
|
|
416
|
+
".azw": "application/vnd.amazon.ebook",
|
|
417
|
+
".bin": "application/octet-stream",
|
|
418
|
+
".bmp": "image/bmp",
|
|
419
|
+
".bz": "application/x-bzip",
|
|
420
|
+
".bz2": "application/x-bzip2",
|
|
421
|
+
".cda": "application/x-cdf",
|
|
422
|
+
".csh": "application/x-csh",
|
|
423
|
+
".css": "text/css",
|
|
424
|
+
".csv": "text/csv",
|
|
425
|
+
".doc": "application/msword",
|
|
426
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
427
|
+
".eot": "application/vnd.ms-fontobject",
|
|
428
|
+
".epub": "application/epub+zip",
|
|
429
|
+
".gz": "application/gzip",
|
|
430
|
+
".gif": "image/gif",
|
|
431
|
+
".htm": "text/html",
|
|
432
|
+
".html": "text/html",
|
|
433
|
+
".ico": "image/vnd.microsoft.icon",
|
|
434
|
+
".ics": "text/calendar",
|
|
435
|
+
".jar": "application/java-archive",
|
|
436
|
+
".jpeg": "image/jpeg",
|
|
437
|
+
".jpg": "image/jpeg",
|
|
438
|
+
".js": "text/javascript",
|
|
439
|
+
".json": "application/json",
|
|
440
|
+
".jsonld": "application/ld+json",
|
|
441
|
+
".mid": "audio/midi audio/x-midi",
|
|
442
|
+
".midi": "audio/midi audio/x-midi",
|
|
443
|
+
".mjs": "text/javascript",
|
|
444
|
+
".mp3": "audio/mpeg",
|
|
445
|
+
".mp4": "video/mp4",
|
|
446
|
+
".mpeg": "video/mpeg",
|
|
447
|
+
".mpkg": "application/vnd.apple.installer+xml",
|
|
448
|
+
".odp": "application/vnd.oasis.opendocument.presentation",
|
|
449
|
+
".ods": "application/vnd.oasis.opendocument.spreadsheet",
|
|
450
|
+
".odt": "application/vnd.oasis.opendocument.text",
|
|
451
|
+
".oga": "audio/ogg",
|
|
452
|
+
".ogv": "video/ogg",
|
|
453
|
+
".ogx": "application/ogg",
|
|
454
|
+
".opus": "audio/opus",
|
|
455
|
+
".otf": "font/otf",
|
|
456
|
+
".png": "image/png",
|
|
457
|
+
".pdf": "application/pdf",
|
|
458
|
+
".php": "application/x-httpd-php",
|
|
459
|
+
".ppt": "application/vnd.ms-powerpoint",
|
|
460
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
461
|
+
".rar": "application/vnd.rar",
|
|
462
|
+
".rtf": "application/rtf",
|
|
463
|
+
".sh": "application/x-sh",
|
|
464
|
+
".svg": "image/svg+xml",
|
|
465
|
+
".swf": "application/x-shockwave-flash",
|
|
466
|
+
".tar": "application/x-tar",
|
|
467
|
+
".tif": "image/tiff",
|
|
468
|
+
".tiff": "image/tiff",
|
|
469
|
+
".ts": "video/mp2t",
|
|
470
|
+
".ttf": "font/ttf",
|
|
471
|
+
".txt": "text/plain",
|
|
472
|
+
".vsd": "application/vnd.visio",
|
|
473
|
+
".wav": "audio/wav",
|
|
474
|
+
".weba": "audio/webm",
|
|
475
|
+
".webm": "video/webm",
|
|
476
|
+
".webp": "image/webp",
|
|
477
|
+
".woff": "font/woff",
|
|
478
|
+
".woff2": "font/woff2",
|
|
479
|
+
".xhtml": "application/xhtml+xml",
|
|
480
|
+
".xls": "application/vnd.ms-excel",
|
|
481
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
482
|
+
".xml": "application/xml",
|
|
483
|
+
".xul": "application/vnd.mozilla.xul+xml",
|
|
484
|
+
".zip": "application/zip",
|
|
485
|
+
".3gp": "video/3gpp; audio/3gpp",
|
|
486
|
+
".3g2": "video/3gpp2; audio/3gpp2",
|
|
487
|
+
".7z": "application/x-7z-compressed"
|
|
488
|
+
}
|
|
489
|
+
},
|
|
490
|
+
defaultContentType: {
|
|
491
|
+
type: "string",
|
|
492
|
+
required: false,
|
|
493
|
+
defaultValue: "application/octet-stream"
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}, "options"), "bad options");
|
|
497
|
+
if (!statSync(this.staticOptions.directory).isDirectory()) {
|
|
498
|
+
throw new Error(`options.directory ${this.staticOptions.directory} not a directory`);
|
|
499
|
+
}
|
|
500
|
+
if (this.staticOptions.index404 && !existsSync(resolve(this.staticOptions.directory, this.staticOptions.index404))) {
|
|
501
|
+
throw new Error(`options.index404 ${this.staticOptions.index404} not a found`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
async run(req, res, pathTokens, prePathTokens = []) {
|
|
505
|
+
const { directory, allowGetJSON, allowListJSON, list, index, contentTypes, defaultContentType } = this.staticOptions;
|
|
506
|
+
const level = prePathTokens.length;
|
|
507
|
+
if (String(req.method).toLowerCase() === "get") {
|
|
508
|
+
const realPath = resolve(directory, req.path.split("/").map(s => s.trim()).filter(s => s).slice(level).join("/"));
|
|
509
|
+
req.logger.debug("static get %s", realPath);
|
|
510
|
+
if (existsSync(realPath)) {
|
|
511
|
+
if (statSync(realPath).isDirectory()) {
|
|
512
|
+
// directory
|
|
513
|
+
const indexPath = resolve(realPath, index);
|
|
514
|
+
if (index && existsSync(indexPath) && statSync(indexPath).isFile()) {
|
|
515
|
+
// index file exists
|
|
516
|
+
const ext = extname(indexPath);
|
|
517
|
+
const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
|
|
518
|
+
await outputFile(indexPath, contentType, req, res, allowGetJSON);
|
|
519
|
+
}
|
|
520
|
+
else {
|
|
521
|
+
// index doesn't exists
|
|
522
|
+
if (list) {
|
|
523
|
+
// generate list
|
|
524
|
+
await generateList(realPath, req, res, allowListJSON);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
else {
|
|
529
|
+
// direct file access
|
|
530
|
+
const ext = extname(realPath);
|
|
531
|
+
const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
|
|
532
|
+
await outputFile(realPath, contentType, req, res, allowGetJSON);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
if (this.staticOptions.index404) {
|
|
537
|
+
const realPath = resolve(this.staticOptions.directory, this.staticOptions.index404);
|
|
538
|
+
if (existsSync(realPath)) {
|
|
539
|
+
const ext = extname(realPath);
|
|
540
|
+
const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
|
|
541
|
+
await outputFile(realPath, contentType, req, res, allowGetJSON, this.staticOptions.index404Status);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
return !res.headersSent ? super.run(req, res, pathTokens, prePathTokens) : false;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* # APIRouter
|
|
549
|
+
*
|
|
550
|
+
* src/server.js
|
|
551
|
+
* ```typescript
|
|
552
|
+
*import { App, APIRouter } from "@miqro/core";
|
|
553
|
+
*const app = new App();
|
|
554
|
+
*app.use(APIRouter({ dirname: resolve(__dirname, "api") }));
|
|
555
|
+
*app.listen(8080);
|
|
556
|
+
* ```
|
|
557
|
+
*
|
|
558
|
+
* src/api/user/post.js
|
|
559
|
+
*
|
|
560
|
+
* ```typescript
|
|
561
|
+
*import { ReadBuffer, JSONParser, APIRoute } from "@miqro/core";
|
|
562
|
+
*
|
|
563
|
+
*const route: APIRoute = {
|
|
564
|
+
* middleware: [ReadBuffer(), JSONParser()],
|
|
565
|
+
* request: {
|
|
566
|
+
* query: { ... },
|
|
567
|
+
* body: { ... },
|
|
568
|
+
* ...
|
|
569
|
+
* },
|
|
570
|
+
* response: {
|
|
571
|
+
* ...
|
|
572
|
+
* },
|
|
573
|
+
* handler: async (ctx: Context) => {
|
|
574
|
+
* return {
|
|
575
|
+
* status: 200,
|
|
576
|
+
* body: {
|
|
577
|
+
* status: "OK"
|
|
578
|
+
* }
|
|
579
|
+
* };
|
|
580
|
+
* }
|
|
581
|
+
*}
|
|
582
|
+
*export default route;
|
|
583
|
+
* ```
|
|
584
|
+
*/
|
|
585
|
+
export async function APIRouter(options, logger) {
|
|
586
|
+
const { dirname } = assertNotUndefined(DEFAULT_PARSER.parse(options, APIRouterOptionsSchema, "options"), "bad options");
|
|
587
|
+
if (typeof dirname !== "string") {
|
|
588
|
+
throw new Error(`options.dirname must be defined!`);
|
|
589
|
+
}
|
|
590
|
+
if (!existsSync(dirname) || !lstatSync(dirname).isDirectory()) {
|
|
591
|
+
throw new Error(`${dirname} not a directory!`);
|
|
592
|
+
}
|
|
593
|
+
const apiName = options.apiName !== undefined ? options.apiName : basename(dirname);
|
|
594
|
+
const apiPath = options.path !== undefined ? options.path : "";
|
|
595
|
+
return await traverseAPIRouteDir(apiName.toUpperCase(), dirname, apiPath, undefined, logger);
|
|
596
|
+
}
|
|
597
|
+
async function traverseAPIRouteDir(featureName, dirname, basePath = "/", router = new Router(), logger) {
|
|
598
|
+
if (logger) {
|
|
599
|
+
logger.trace("loading routes from [%s]", dirname);
|
|
600
|
+
}
|
|
601
|
+
const files = readdirSync(dirname);
|
|
602
|
+
const dirs = files.filter(f => lstatSync(join(dirname, f)).isDirectory());
|
|
603
|
+
const methods = files.filter(f => !lstatSync(join(dirname, f)).isDirectory());
|
|
604
|
+
const postFolder = [];
|
|
605
|
+
for (const f of methods) {
|
|
606
|
+
const { name, ext } = parse(f);
|
|
607
|
+
if (name !== "index" && ((ext === ".ts" || ext === ".js") && name.slice(-2) !== ".d")) {
|
|
608
|
+
const filePath = join(dirname, f);
|
|
609
|
+
//console.log("dirname=%s f=%s", dirname, f);
|
|
610
|
+
let route = await import(filePath);
|
|
611
|
+
//if ((route as any).default && (route as any).__esModule === true) {
|
|
612
|
+
if (route.default) {
|
|
613
|
+
route = route.default;
|
|
614
|
+
// ugly hack when import is importing a commonjs that exports default
|
|
615
|
+
if (route.default) {
|
|
616
|
+
route = route.default;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
//const ___filePath = filePath + ext;
|
|
620
|
+
const ___filePath = filePath;
|
|
621
|
+
//let routeMethods: Method[] = [name] as Method[];
|
|
622
|
+
let routeMethod = name;
|
|
623
|
+
if (typeof route === "function") {
|
|
624
|
+
route = {
|
|
625
|
+
handler: route
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
else {
|
|
629
|
+
if (typeof route.method !== "undefined" && ( /*!(route.method instanceof Array) &&*/(typeof route.method !== "string"))) {
|
|
630
|
+
//throw new Error(`${resolve(dirname, name)} doesn't export method as a string or string array`);
|
|
631
|
+
throw new Error(`${resolve(dirname, name)} doesnt export method as a string`);
|
|
632
|
+
}
|
|
633
|
+
else if (typeof route.method !== "undefined") {
|
|
634
|
+
routeMethod = route.method; //route.method instanceof Array ? route.method : [route.method];
|
|
635
|
+
}
|
|
636
|
+
if (typeof route.path !== "string" && typeof route.path !== "undefined" /* && !(route.path instanceof Array)*/) {
|
|
637
|
+
//throw new Error(`${resolve(dirname, name)} doesn't export path as a string or a string array`);
|
|
638
|
+
throw new Error(`${resolve(dirname, name)} doesnt export path as a string`);
|
|
639
|
+
}
|
|
640
|
+
if ((!(route.handler instanceof Array) && typeof route.handler !== "function" && !isMinimalRouter(route.handler)) || typeof route.handler === "undefined") {
|
|
641
|
+
throw new Error(`${resolve(dirname, name)} doesnt export handler as a function or an array`);
|
|
642
|
+
}
|
|
643
|
+
if (typeof route.name !== "string" && typeof route.name !== "undefined") {
|
|
644
|
+
throw new Error(`${resolve(dirname, name)} doesnt export name as a string`);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
try {
|
|
648
|
+
route = assertNotUndefined(DEFAULT_PARSER.parse(route, APIRouteSchema, ___filePath), `error parsing [${___filePath}]`);
|
|
649
|
+
}
|
|
650
|
+
catch (e) {
|
|
651
|
+
console.error("error parsing " + ___filePath);
|
|
652
|
+
throw e;
|
|
653
|
+
}
|
|
654
|
+
//const paths = route.path instanceof Array ? route.path : route.path === undefined ? [route.method && route.method.indexOf(name as Method) === -1 ? `/${name}` : "/"] : [route.path];
|
|
655
|
+
const p = route.path === undefined ? route.method && route.method.indexOf(name) === -1 ? `/${name}` : "/" : route.path;
|
|
656
|
+
//for (let i = 0; i < paths.length; i++) {
|
|
657
|
+
//const p = paths[i];
|
|
658
|
+
if (typeof p !== "string" || !p) {
|
|
659
|
+
throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
|
|
660
|
+
}
|
|
661
|
+
const path = normalizePath(`${basePath}${p && p !== "/" ? `${p}` : p}`);
|
|
662
|
+
const subName = (p.charAt(0) === "/" ? p.substring(1) : p).replace(/[^a-z0-9+]+/gi, '_');
|
|
663
|
+
const routeName = route.name ? route.name : name;
|
|
664
|
+
//const identifier = route.identifier ? route.identifier : getPathIdentifier(path, routeMethod);
|
|
665
|
+
/*let newFeatureSubPath = `${featureName}_${route.name ? route.name : name}${routeName !== subName ? `_${subName}` : ""}`.toUpperCase();
|
|
666
|
+
|
|
667
|
+
newFeatureSubPath = newFeatureSubPath.length > 1 && newFeatureSubPath.charAt(newFeatureSubPath.length - 1) === "_" ? newFeatureSubPath.substring(0, newFeatureSubPath.length - 1) : newFeatureSubPath;*/
|
|
668
|
+
/*if (features[identifier]) {
|
|
669
|
+
throw new Error(`${___filePath} feature name collides with ${(features[identifier] as any).___filePath}`)
|
|
670
|
+
}*/
|
|
671
|
+
if (route.identifier && route.identifier === "__prototype__" || route.identifier === "__proto__") {
|
|
672
|
+
throw new Error(`invalid feature name ${route.identifier}`);
|
|
673
|
+
}
|
|
674
|
+
const useCallArgs = [route.handler, path, routeMethod !== "use" && routeMethod !== "USE" ? routeMethod : undefined, {
|
|
675
|
+
identifier: route.identifier,
|
|
676
|
+
apiName: route.apiName,
|
|
677
|
+
name: route.name,
|
|
678
|
+
description: route.description,
|
|
679
|
+
parser: route.parser,
|
|
680
|
+
middleware: route.middleware,
|
|
681
|
+
session: route.session,
|
|
682
|
+
policy: route.policy,
|
|
683
|
+
request: route.request,
|
|
684
|
+
response: route.response ? route.response : true // ResponseHandler added by default to an APIRoute
|
|
685
|
+
}];
|
|
686
|
+
if (route.postFolder) {
|
|
687
|
+
postFolder.push(useCallArgs);
|
|
688
|
+
}
|
|
689
|
+
else {
|
|
690
|
+
router.use(...useCallArgs);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
for (const f of dirs) {
|
|
695
|
+
const { name } = parse(f);
|
|
696
|
+
router = await traverseAPIRouteDir(`${featureName}_${name}`.toUpperCase(), join(dirname, f), `${basePath}/${name}`, router, logger);
|
|
697
|
+
}
|
|
698
|
+
for (const post of postFolder) {
|
|
699
|
+
router.use(...post);
|
|
700
|
+
}
|
|
701
|
+
return router;
|
|
702
|
+
}
|
|
703
|
+
;
|
|
704
|
+
//# sourceMappingURL=router.js.map
|