@miqro/core 1.2.4 → 1.3.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/README.md +43 -27
- package/dist/handler/api-handler.d.ts +5 -0
- package/dist/handler/api-handler.js +12 -4
- package/dist/handler/api-handler.js.map +1 -0
- package/dist/handler/api-router-utils.js +10 -2
- package/dist/handler/api-router-utils.js.map +1 -0
- package/dist/handler/api-router.d.ts +1 -2
- package/dist/handler/api-router.js +1 -0
- package/dist/handler/api-router.js.map +1 -0
- package/dist/handler/app.d.ts +1 -2
- package/dist/handler/app.js +96 -13
- package/dist/handler/app.js.map +1 -0
- package/dist/handler/common/context.d.ts +57 -0
- package/dist/handler/common/context.js +123 -0
- package/dist/handler/common/context.js.map +1 -0
- package/dist/handler/common/helpers.js +1 -0
- package/dist/handler/common/helpers.js.map +1 -0
- package/dist/handler/common/index.d.ts +2 -45
- package/dist/handler/common/index.js +13 -110
- package/dist/handler/common/index.js.map +1 -0
- package/dist/handler/common/router-utils.d.ts +26 -0
- package/dist/handler/common/router-utils.js +59 -0
- package/dist/handler/common/router-utils.js.map +1 -0
- package/dist/handler/{router.d.ts → common/router.d.ts} +7 -16
- package/dist/handler/common/router.js +76 -0
- package/dist/handler/common/router.js.map +1 -0
- package/dist/handler/common/tokenize-match.d.ts +18 -9
- package/dist/handler/common/tokenize-match.js +36 -28
- package/dist/handler/common/tokenize-match.js.map +1 -0
- package/dist/handler/feature-router.d.ts +1 -2
- package/dist/handler/feature-router.js +3 -2
- package/dist/handler/feature-router.js.map +1 -0
- package/dist/handler/index.d.ts +1 -5
- package/dist/handler/index.js +2 -6
- package/dist/handler/index.js.map +1 -0
- package/dist/{middleware → handler/middleware}/buffer.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/buffer.js +3 -2
- package/dist/handler/middleware/buffer.js.map +1 -0
- package/dist/handler/middleware/cookie.d.ts +4 -0
- package/dist/handler/middleware/cookie.js +18 -0
- package/dist/handler/middleware/cookie.js.map +1 -0
- package/dist/{middleware → handler/middleware}/cors.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/cors.js +3 -2
- package/dist/handler/middleware/cors.js.map +1 -0
- package/dist/{middleware → handler/middleware}/form.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/form.js +8 -5
- package/dist/handler/middleware/form.js.map +1 -0
- package/dist/handler/middleware/group.d.ts +3 -0
- package/dist/handler/{group.js → middleware/group.js} +3 -2
- package/dist/handler/middleware/group.js.map +1 -0
- package/dist/handler/middleware/index.d.ts +13 -0
- package/dist/handler/middleware/index.js +64 -0
- package/dist/handler/middleware/index.js.map +1 -0
- package/dist/{middleware → handler/middleware}/json.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/json.js +3 -2
- package/dist/handler/middleware/json.js.map +1 -0
- package/dist/{middleware → handler/middleware}/logger.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/logger.js +1 -0
- package/dist/handler/middleware/logger.js.map +1 -0
- package/dist/handler/{parse.d.ts → middleware/parse.d.ts} +4 -3
- package/dist/handler/{parse.js → middleware/parse.js} +17 -7
- package/dist/handler/middleware/parse.js.map +1 -0
- package/dist/handler/middleware/session.d.ts +21 -0
- package/dist/handler/middleware/session.js +140 -0
- package/dist/handler/middleware/session.js.map +1 -0
- package/dist/handler/middleware/tag.d.ts +4 -0
- package/dist/handler/middleware/tag.js +14 -0
- package/dist/handler/middleware/tag.js.map +1 -0
- package/dist/{middleware → handler/middleware}/text.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/text.js +3 -2
- package/dist/handler/middleware/text.js.map +1 -0
- package/dist/handler/proxy.js +5 -11
- package/dist/handler/proxy.js.map +1 -0
- package/dist/handler/{html.d.ts → response/html.d.ts} +1 -1
- package/dist/handler/{html.js → response/html.js} +1 -0
- package/dist/handler/response/html.js.map +1 -0
- package/dist/handler/response/index.d.ts +3 -0
- package/dist/{middleware → handler/response}/index.js +3 -7
- package/dist/handler/response/index.js.map +1 -0
- package/dist/handler/{response.d.ts → response/json.d.ts} +1 -1
- package/dist/handler/{response.js → response/json.js} +3 -3
- package/dist/handler/response/json.js.map +1 -0
- package/dist/handler/response/result.d.ts +4 -0
- package/dist/handler/{result.js → response/result.js} +8 -8
- package/dist/handler/response/result.js.map +1 -0
- package/dist/index.d.ts +0 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -0
- package/dist/util/cli/index.js +1 -0
- package/dist/util/cli/index.js.map +1 -0
- package/dist/util/config/browser.js +1 -0
- package/dist/util/config/browser.js.map +1 -0
- package/dist/util/config/config.js +1 -0
- package/dist/util/config/config.js.map +1 -0
- package/dist/util/config/featuretoggle.js +1 -0
- package/dist/util/config/featuretoggle.js.map +1 -0
- package/dist/util/config/index.js +1 -0
- package/dist/util/config/index.js.map +1 -0
- package/dist/util/cookie/cookie.d.ts +51 -0
- package/dist/util/cookie/cookie.js +168 -0
- package/dist/util/cookie/cookie.js.map +1 -0
- package/dist/util/cookie/index.d.ts +16 -0
- package/dist/util/cookie/index.js +9 -0
- package/dist/util/cookie/index.js.map +1 -0
- package/dist/util/error/configfilenotfound.js +1 -0
- package/dist/util/error/configfilenotfound.js.map +1 -0
- package/dist/util/error/forbiddenerror.js +1 -0
- package/dist/util/error/forbiddenerror.js.map +1 -0
- package/dist/util/error/index.js +1 -0
- package/dist/util/error/index.js.map +1 -0
- package/dist/util/error/named.js +1 -0
- package/dist/util/error/named.js.map +1 -0
- package/dist/util/error/notfound.js +1 -0
- package/dist/util/error/notfound.js.map +1 -0
- package/dist/util/error/notimplemented.js +1 -0
- package/dist/util/error/notimplemented.js.map +1 -0
- package/dist/util/error/parsererror.js +1 -0
- package/dist/util/error/parsererror.js.map +1 -0
- package/dist/util/error/unauthorizederror.js +1 -0
- package/dist/util/error/unauthorizederror.js.map +1 -0
- package/dist/util/index.js +3 -0
- package/dist/util/index.js.map +1 -0
- package/dist/util/loader/index.js +1 -0
- package/dist/util/loader/index.js.map +1 -0
- package/dist/util/logger/common.js +1 -0
- package/dist/util/logger/common.js.map +1 -0
- package/dist/util/logger/factory.js +1 -0
- package/dist/util/logger/factory.js.map +1 -0
- package/dist/util/logger/formatter.js +1 -0
- package/dist/util/logger/formatter.js.map +1 -0
- package/dist/util/logger/index.js +1 -0
- package/dist/util/logger/index.js.map +1 -0
- package/dist/util/logger/logger.js +6 -2
- package/dist/util/logger/logger.js.map +1 -0
- package/dist/util/logger/transport.js +1 -0
- package/dist/util/logger/transport.js.map +1 -0
- package/dist/util/parser/common.d.ts +5 -5
- package/dist/util/parser/common.js +1 -0
- package/dist/util/parser/common.js.map +1 -0
- package/dist/util/parser/get.js +7 -1
- package/dist/util/parser/get.js.map +1 -0
- package/dist/util/parser/index.js +1 -0
- package/dist/util/parser/index.js.map +1 -0
- package/dist/util/parser/parser.d.ts +3 -3
- package/dist/util/parser/parser.js +20 -11
- package/dist/util/parser/parser.js.map +1 -0
- package/dist/util/parser/types/any.js +1 -0
- package/dist/util/parser/types/any.js.map +1 -0
- package/dist/util/parser/types/array.js +1 -0
- package/dist/util/parser/types/array.js.map +1 -0
- package/dist/util/parser/types/boolean.js +1 -0
- package/dist/util/parser/types/boolean.js.map +1 -0
- package/dist/util/parser/types/email.js +1 -0
- package/dist/util/parser/types/email.js.map +1 -0
- package/dist/util/parser/types/enum.js +1 -0
- package/dist/util/parser/types/enum.js.map +1 -0
- package/dist/util/parser/types/index.js +1 -0
- package/dist/util/parser/types/index.js.map +1 -0
- package/dist/util/parser/types/multiple.js +6 -2
- package/dist/util/parser/types/multiple.js.map +1 -0
- package/dist/util/parser/types/nested.js +1 -0
- package/dist/util/parser/types/nested.js.map +1 -0
- package/dist/util/parser/types/number.js +1 -0
- package/dist/util/parser/types/number.js.map +1 -0
- package/dist/util/parser/types/object.js +1 -0
- package/dist/util/parser/types/object.js.map +1 -0
- package/dist/util/parser/types/regex.js +1 -0
- package/dist/util/parser/types/regex.js.map +1 -0
- package/dist/util/parser/types/string.js +1 -0
- package/dist/util/parser/types/string.js.map +1 -0
- package/dist/util/parser/types/url.js +1 -0
- package/dist/util/parser/types/url.js.map +1 -0
- package/dist/util/request/common.d.ts +10 -0
- package/dist/util/request/common.js +100 -1
- package/dist/util/request/common.js.map +1 -0
- package/dist/util/request/index.js +143 -199
- package/dist/util/request/index.js.map +1 -0
- package/dist/util/session/common.d.ts +16 -0
- package/dist/util/session/common.js +49 -0
- package/dist/util/session/common.js.map +1 -0
- package/dist/util/session/index.d.ts +2 -16
- package/dist/util/session/index.js +13 -46
- package/dist/util/session/index.js.map +1 -0
- package/dist/util/session/service.d.ts +26 -0
- package/dist/util/session/service.js +143 -0
- package/dist/util/session/service.js.map +1 -0
- package/dist/util/test/app.js +5 -1
- package/dist/util/test/app.js.map +1 -0
- package/dist/util/test/common.js +1 -0
- package/dist/util/test/common.js.map +1 -0
- package/dist/util/test/index.js +1 -0
- package/dist/util/test/index.js.map +1 -0
- package/dist/util/uuid/index.d.ts +7 -0
- package/dist/util/uuid/index.js +8 -0
- package/dist/util/uuid/index.js.map +1 -0
- package/dist/util/uuid/regex.d.ts +2 -0
- package/dist/util/uuid/regex.js +5 -0
- package/dist/util/uuid/regex.js.map +1 -0
- package/dist/util/uuid/rng.d.ts +1 -0
- package/dist/util/uuid/rng.js +18 -0
- package/dist/util/uuid/rng.js.map +1 -0
- package/dist/util/uuid/stringify.d.ts +2 -0
- package/dist/util/uuid/stringify.js +50 -0
- package/dist/util/uuid/stringify.js.map +1 -0
- package/dist/util/uuid/v4.d.ts +5 -0
- package/dist/util/uuid/v4.js +27 -0
- package/dist/util/uuid/v4.js.map +1 -0
- package/dist/util/uuid/validate.d.ts +2 -0
- package/dist/util/uuid/validate.js +12 -0
- package/dist/util/uuid/validate.js.map +1 -0
- package/package.json +12 -21
- package/src/handler/api-handler.ts +56 -0
- package/src/handler/api-router-utils.ts +101 -0
- package/src/handler/api-router.ts +60 -0
- package/src/handler/app.ts +138 -0
- package/src/handler/common/context.ts +161 -0
- package/src/handler/common/helpers.ts +11 -0
- package/src/handler/common/index.ts +3 -0
- package/src/handler/common/router-utils.ts +67 -0
- package/src/handler/common/router.ts +70 -0
- package/src/handler/common/tokenize-match.ts +152 -0
- package/src/handler/feature-router.ts +90 -0
- package/src/handler/index.ts +8 -0
- package/src/handler/middleware/buffer.ts +79 -0
- package/src/handler/middleware/cookie.ts +19 -0
- package/src/handler/middleware/cors.ts +98 -0
- package/src/handler/middleware/form.ts +53 -0
- package/src/handler/middleware/group.ts +28 -0
- package/src/handler/middleware/index.ts +52 -0
- package/src/handler/middleware/json.ts +50 -0
- package/src/handler/middleware/logger.ts +18 -0
- package/src/handler/middleware/parse.ts +93 -0
- package/src/handler/middleware/session.ts +155 -0
- package/src/handler/middleware/tag.ts +15 -0
- package/src/handler/middleware/text.ts +40 -0
- package/src/handler/proxy.ts +44 -0
- package/src/handler/response/html.ts +36 -0
- package/src/handler/response/index.ts +3 -0
- package/src/handler/response/json.ts +19 -0
- package/src/handler/response/result.ts +40 -0
- package/src/index.ts +2 -0
- package/src/util/cli/index.ts +57 -0
- package/src/util/config/browser.ts +5 -0
- package/src/util/config/config.ts +93 -0
- package/src/util/config/featuretoggle.ts +6 -0
- package/src/util/config/index.ts +3 -0
- package/src/util/cookie/cookie.ts +207 -0
- package/src/util/cookie/index.ts +6 -0
- package/src/util/error/configfilenotfound.ts +8 -0
- package/src/util/error/forbiddenerror.ts +8 -0
- package/src/util/error/index.ts +6 -0
- package/src/util/error/named.ts +3 -0
- package/src/util/error/notfound.ts +8 -0
- package/src/util/error/notimplemented.ts +8 -0
- package/src/util/error/parsererror.ts +10 -0
- package/src/util/error/unauthorizederror.ts +8 -0
- package/src/util/index.ts +11 -0
- package/src/util/loader/index.ts +67 -0
- package/src/util/logger/common.ts +6 -0
- package/src/util/logger/factory.ts +45 -0
- package/src/util/logger/formatter.ts +9 -0
- package/src/util/logger/index.ts +6 -0
- package/src/util/logger/logger.ts +114 -0
- package/src/util/logger/transport.ts +69 -0
- package/src/util/parser/common.ts +81 -0
- package/src/util/parser/get.ts +42 -0
- package/src/util/parser/index.ts +6 -0
- package/src/util/parser/parser.ts +235 -0
- package/src/util/parser/types/any.ts +8 -0
- package/src/util/parser/types/array.ts +73 -0
- package/src/util/parser/types/boolean.ts +13 -0
- package/src/util/parser/types/email.ts +26 -0
- package/src/util/parser/types/enum.ts +29 -0
- package/src/util/parser/types/index.ts +12 -0
- package/src/util/parser/types/multiple.ts +36 -0
- package/src/util/parser/types/nested.ts +19 -0
- package/src/util/parser/types/number.ts +34 -0
- package/src/util/parser/types/object.ts +10 -0
- package/src/util/parser/types/regex.ts +17 -0
- package/src/util/parser/types/string.ts +23 -0
- package/src/util/parser/types/url.ts +35 -0
- package/src/util/request/common.ts +193 -0
- package/src/util/request/index.ts +230 -0
- package/src/util/session/common.ts +63 -0
- package/src/util/session/index.ts +2 -0
- package/src/util/session/service.ts +154 -0
- package/src/util/test/app.ts +44 -0
- package/src/util/test/common.ts +17 -0
- package/src/util/test/index.ts +2 -0
- package/src/util/uuid/index.ts +5 -0
- package/src/util/uuid/regex.ts +2 -0
- package/src/util/uuid/rng.ts +14 -0
- package/src/util/uuid/stringify.ts +53 -0
- package/src/util/uuid/v4.ts +30 -0
- package/src/util/uuid/validate.ts +8 -0
- package/tsconfig.json +32 -0
- package/dist/handler/common/response.d.ts +0 -13
- package/dist/handler/common/response.js +0 -54
- package/dist/handler/error.d.ts +0 -2
- package/dist/handler/error.js +0 -46
- package/dist/handler/group.d.ts +0 -3
- package/dist/handler/result.d.ts +0 -4
- package/dist/handler/router.js +0 -119
- package/dist/middleware/index.d.ts +0 -6
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { existsSync, lstatSync } from "fs";
|
|
2
|
+
import { basename } from "path";
|
|
3
|
+
import { Logger } from "../util";
|
|
4
|
+
import { APIHandlerOptions } from "./api-handler";
|
|
5
|
+
import { traverseAPIRouteDir } from "./api-router-utils";
|
|
6
|
+
import { Router, Method } from "./common";
|
|
7
|
+
import { FeatureRouter } from "./feature-router";
|
|
8
|
+
|
|
9
|
+
export interface APIRoute extends APIHandlerOptions {
|
|
10
|
+
name?: string;
|
|
11
|
+
description?: string;
|
|
12
|
+
method?: Method | Method[];
|
|
13
|
+
path?: string | string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* # APIRouter
|
|
18
|
+
*
|
|
19
|
+
* src/server.js
|
|
20
|
+
* ```typescript
|
|
21
|
+
*import { App, APIRouter } from "@miqro/core";
|
|
22
|
+
*const app = new App();
|
|
23
|
+
*app.use(APIRouter({ dirname: resolve(__dirname, "api") }));
|
|
24
|
+
*app.listen(8080);
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* src/api/user/post.js
|
|
28
|
+
*
|
|
29
|
+
* ```typescript
|
|
30
|
+
*import { ReadBuffer, JSONParser, APIRoute } from "@miqro/core";
|
|
31
|
+
*
|
|
32
|
+
*const route: APIRoute = {
|
|
33
|
+
* middleware: [ReadBuffer(), JSONParser()]
|
|
34
|
+
* query: { ... },
|
|
35
|
+
* body: { ... },
|
|
36
|
+
* result: { ... },
|
|
37
|
+
* handler: async (ctx: Context) => {
|
|
38
|
+
* return {
|
|
39
|
+
* status: "OK"
|
|
40
|
+
* };
|
|
41
|
+
* }
|
|
42
|
+
*}
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export const APIRouter = (options: {
|
|
46
|
+
dirname: string;
|
|
47
|
+
apiName?: string;
|
|
48
|
+
path?: string;
|
|
49
|
+
}, logger?: Logger): Router => {
|
|
50
|
+
const { dirname } = options;
|
|
51
|
+
if (typeof dirname !== "string") {
|
|
52
|
+
throw new Error(`options.dirname must be defined!`);
|
|
53
|
+
}
|
|
54
|
+
if (!existsSync(dirname) || !lstatSync(dirname).isDirectory()) {
|
|
55
|
+
throw new Error(`${dirname} not a directory!`);
|
|
56
|
+
}
|
|
57
|
+
const apiName = options.apiName !== undefined ? options.apiName : basename(dirname);
|
|
58
|
+
const apiPath = options.path !== undefined ? options.path : `/${apiName}`;
|
|
59
|
+
return FeatureRouter(traverseAPIRouteDir(apiName.toUpperCase(), dirname, apiPath, undefined, logger), logger);
|
|
60
|
+
};
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { createServer, IncomingMessage, RequestListener, Server, ServerResponse } from "http";
|
|
2
|
+
import { Logger } from "../util";
|
|
3
|
+
import { Router, Context, ErrorHandler } from "./common";
|
|
4
|
+
|
|
5
|
+
export interface AppOptions {
|
|
6
|
+
newRequestLogger?: (req: IncomingMessage) => Logger;
|
|
7
|
+
newContext?: (req: IncomingMessage, res: ServerResponse) => Context;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class App extends Router {
|
|
11
|
+
public readonly listener: RequestListener;
|
|
12
|
+
|
|
13
|
+
constructor(private appOptions?: AppOptions) {
|
|
14
|
+
super();
|
|
15
|
+
const errorHandler = DefaultErrorHandler();
|
|
16
|
+
this.listener = async (req, res) => {
|
|
17
|
+
const ctx = this.appOptions && this.appOptions.newContext ?
|
|
18
|
+
this.appOptions.newContext(req, res) :
|
|
19
|
+
new Context(
|
|
20
|
+
req,
|
|
21
|
+
res,
|
|
22
|
+
this.appOptions && this.appOptions.newRequestLogger ?
|
|
23
|
+
this.appOptions.newRequestLogger(req) :
|
|
24
|
+
undefined);
|
|
25
|
+
ctx.logger.trace(`request received`);
|
|
26
|
+
try {
|
|
27
|
+
await this.run(ctx);
|
|
28
|
+
if (!ctx.res.headersSent) {
|
|
29
|
+
ctx.end({
|
|
30
|
+
headers: TEXT_HEADERS,
|
|
31
|
+
status: STATUS.NOT_FOUND,
|
|
32
|
+
body: "NOT FOUND"
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
} catch (e: any) {
|
|
36
|
+
try {
|
|
37
|
+
if (!ctx.res.headersSent) {
|
|
38
|
+
await errorHandler(e, ctx);
|
|
39
|
+
if (!ctx.res.headersSent) {
|
|
40
|
+
ctx.logger.error(e);
|
|
41
|
+
ctx.end({
|
|
42
|
+
headers: TEXT_HEADERS,
|
|
43
|
+
status: STATUS.ERROR,
|
|
44
|
+
body: "SERVER ERROR"
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
} catch (e3) {
|
|
49
|
+
ctx.logger.error(e3);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
public listen(...args: any[]): Server {
|
|
55
|
+
return createServer(this.listener).listen(...args)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const TEXT_HEADERS = {
|
|
60
|
+
["Content-Type"]: "plain/text; charset=utf-8"
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const STATUS = {
|
|
64
|
+
ERROR: 503,
|
|
65
|
+
BAD_REQUEST: 400,
|
|
66
|
+
NOT_FOUND: 404,
|
|
67
|
+
NOT_IMPLEMENTED: 501,
|
|
68
|
+
FORBIDDEN: 403,
|
|
69
|
+
UNAUTHORIZED: 401,
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const DefaultErrorHandler = (): ErrorHandler<boolean> => {
|
|
73
|
+
return async (e: any, ctx: Context): Promise<boolean> => {
|
|
74
|
+
if (!e || !e.name || e.name === "Error") {
|
|
75
|
+
if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
|
|
76
|
+
ctx.logger.error(e);
|
|
77
|
+
await ctx.end({
|
|
78
|
+
headers: TEXT_HEADERS,
|
|
79
|
+
status: STATUS.ERROR,
|
|
80
|
+
body: `${e && e.message ? e.message : String(e)}. You are seeing this message because NODE_ENV === "development" || NODE_ENV === "test"${e && e.stack ? ` ${e.stack}` : ""}`
|
|
81
|
+
});
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
} else {
|
|
85
|
+
ctx.logger.error(e);
|
|
86
|
+
const name = e && e.name ? e.name : undefined;
|
|
87
|
+
switch (name) {
|
|
88
|
+
case "NotFoundError":
|
|
89
|
+
await ctx.end({
|
|
90
|
+
headers: TEXT_HEADERS,
|
|
91
|
+
status: STATUS.NOT_FOUND,
|
|
92
|
+
body: e.message ? e.message : "NOT FOUND"
|
|
93
|
+
});
|
|
94
|
+
break;
|
|
95
|
+
case "MethodNotImplementedError":
|
|
96
|
+
await ctx.end({
|
|
97
|
+
headers: TEXT_HEADERS,
|
|
98
|
+
status: STATUS.NOT_IMPLEMENTED,
|
|
99
|
+
body: e.message ? e.message : "NOT IMPLEMENTED"
|
|
100
|
+
});
|
|
101
|
+
break;
|
|
102
|
+
case "ForbiddenError":
|
|
103
|
+
await ctx.end({
|
|
104
|
+
headers: TEXT_HEADERS,
|
|
105
|
+
status: STATUS.FORBIDDEN,
|
|
106
|
+
body: e.message ? e.message : "FORBIDDEN"
|
|
107
|
+
});
|
|
108
|
+
break;
|
|
109
|
+
case "UnAuthorizedError":
|
|
110
|
+
await ctx.end({
|
|
111
|
+
headers: TEXT_HEADERS,
|
|
112
|
+
status: STATUS.UNAUTHORIZED,
|
|
113
|
+
body: e.message ? e.message : "UNAUTHORIZED"
|
|
114
|
+
});
|
|
115
|
+
break;
|
|
116
|
+
case "ParseOptionsError":
|
|
117
|
+
case "SequelizeValidationError":
|
|
118
|
+
case "SequelizeEagerLoadingError":
|
|
119
|
+
case "SequelizeUniqueConstraintError":
|
|
120
|
+
await ctx.end({
|
|
121
|
+
headers: TEXT_HEADERS,
|
|
122
|
+
status: STATUS.BAD_REQUEST,
|
|
123
|
+
body: e.message ? e.message : "BAD REQUEST"
|
|
124
|
+
});
|
|
125
|
+
break;
|
|
126
|
+
default:
|
|
127
|
+
await ctx.end({
|
|
128
|
+
headers: TEXT_HEADERS,
|
|
129
|
+
status: STATUS.ERROR,
|
|
130
|
+
body: e.message ? e.message : "SERVER ERROR"
|
|
131
|
+
});
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
return true;
|
|
137
|
+
};
|
|
138
|
+
};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { getLogger, Logger } from "../../util/logger";
|
|
2
|
+
import { Session } from "../../util/session";
|
|
3
|
+
import { IncomingHttpHeaders, IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "http";
|
|
4
|
+
import { normalizePath, parseSearchParams } from "./tokenize-match";
|
|
5
|
+
import { URL } from "url";
|
|
6
|
+
import { defaultLoggerFormatter } from "../../util/logger/formatter";
|
|
7
|
+
import { newURL } from "./helpers";
|
|
8
|
+
import { UUID } from "../../util/uuid";
|
|
9
|
+
import { COOKIE } from "../../util/cookie";
|
|
10
|
+
|
|
11
|
+
export type Method = "get" | "post" | "put" | "delete" | "patch" | "options" | "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS";
|
|
12
|
+
|
|
13
|
+
//export { BAD_REQUEST, METHOD_NOT_IMPLEMENTED, NOT_FOUND, ERROR_RESPONSE, FORBIDDEN, Response, UNAUTHORIZED } from "./response";
|
|
14
|
+
|
|
15
|
+
export type Handler<T = boolean | void | any> = ((ctx: Context) => Promise<T>) | ((ctx: Context) => T);
|
|
16
|
+
|
|
17
|
+
export type ErrorHandler<T = boolean | void | any> = ((e: unknown, ctx: Context) => Promise<T>) | ((e: unknown, ctx: Context) => T);
|
|
18
|
+
|
|
19
|
+
export class Context {
|
|
20
|
+
public readonly url: URL; // new URL(req.url ? req.url : "/", `http://${req.headers.host}`)
|
|
21
|
+
public readonly logger: Logger; // new Logger(...)
|
|
22
|
+
public readonly startMS: number; // Date.now()
|
|
23
|
+
public uuid: string; // a middleware will fill this
|
|
24
|
+
public session?: Session; // a middleware will fill this
|
|
25
|
+
public results: any[]; // handlers will fill this
|
|
26
|
+
public readonly path: string; // normalized path
|
|
27
|
+
public readonly hash: string; // from this.url.hash
|
|
28
|
+
public readonly method: string; // from this.url.method
|
|
29
|
+
public headers: IncomingHttpHeaders; // from this.req.headers
|
|
30
|
+
public readonly cookies: { [name: string]: string }; // a middleware will fill this
|
|
31
|
+
public query: { [name: string]: string | string[] }; // parseSearchParams will fill this with this.url.searchParams
|
|
32
|
+
public params: { [name: string]: string | undefined } = {}; // the router will fill this
|
|
33
|
+
public buffer: Buffer; // empty buffer. middleware must read it
|
|
34
|
+
public readonly remoteAddress?: string;
|
|
35
|
+
public body: any; // a middleware will fill this reading the buffer
|
|
36
|
+
constructor(public readonly req: IncomingMessage, public readonly res: ServerResponse, logger?: Logger) {
|
|
37
|
+
this.body = undefined as any;
|
|
38
|
+
this.res.removeHeader("Date");
|
|
39
|
+
this.url = newURL(req.url ? req.url : "/", `http://${req.headers.host}`) as URL;
|
|
40
|
+
this.method = req.method ? req.method.toUpperCase() as string : "GET";
|
|
41
|
+
this.path = normalizePath(this.url.pathname); // normalized path
|
|
42
|
+
this.hash = this.url.hash;
|
|
43
|
+
this.query = parseSearchParams(this.url.searchParams);
|
|
44
|
+
this.buffer = Buffer.from("");
|
|
45
|
+
this.remoteAddress = req.socket.remoteAddress;
|
|
46
|
+
this.cookies = {}; // a middleware will fill
|
|
47
|
+
this.headers = req.headers;
|
|
48
|
+
this.startMS = Date.now();
|
|
49
|
+
this.uuid = UUID.v4().toString("utf-8");
|
|
50
|
+
this.results = []; // handlers will fill this
|
|
51
|
+
const pathToEnv = this.path.replace(/\//ig, "_").toUpperCase();
|
|
52
|
+
const identifier = `${pathToEnv === "_" ? "" : pathToEnv.substring(1)}${this.method.toUpperCase()}`;
|
|
53
|
+
this.logger = logger ? logger : getLogger(identifier, {
|
|
54
|
+
formatter: ({
|
|
55
|
+
identifier,
|
|
56
|
+
level,
|
|
57
|
+
message,
|
|
58
|
+
}) => defaultLoggerFormatter({
|
|
59
|
+
identifier,
|
|
60
|
+
level,
|
|
61
|
+
message: `${this.method} ${this.url}${this.uuid ? ` [${this.uuid}]` : ""}${this.remoteAddress ? ` (${this.remoteAddress})` : ""}${this.session ?
|
|
62
|
+
` session[${this.session.username}:${this.session.account}]` :
|
|
63
|
+
""
|
|
64
|
+
} ${message}`
|
|
65
|
+
})
|
|
66
|
+
}, false);
|
|
67
|
+
}
|
|
68
|
+
public async close(): Promise<void> {
|
|
69
|
+
return this.end({
|
|
70
|
+
status: 400,
|
|
71
|
+
headers: {
|
|
72
|
+
connection: "close"
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
public addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse {
|
|
77
|
+
const c = this.res.getHeader("Vary");
|
|
78
|
+
const current = c ? c instanceof Array ? c.join(", ") : String(c) : "";
|
|
79
|
+
const nV = value instanceof Array ? value.join(", ") : String(value);
|
|
80
|
+
const newValue = current ? `${current}, ${nV}` : nV;
|
|
81
|
+
return this.res.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
|
|
82
|
+
}
|
|
83
|
+
public setHeader(name: string, value: number | string | ReadonlyArray<string>): ServerResponse {
|
|
84
|
+
return this.res.setHeader(name, value);
|
|
85
|
+
}
|
|
86
|
+
public setCookie(name: string, value: string, options?: {
|
|
87
|
+
encode?: (uriComponent: string | number | boolean) => string;
|
|
88
|
+
maxAge?: number | null;
|
|
89
|
+
domain?: string;
|
|
90
|
+
httpOnly?: boolean;
|
|
91
|
+
secure?: boolean;
|
|
92
|
+
path?: string;
|
|
93
|
+
expires?: Date;
|
|
94
|
+
sameSite?: "lax" | "strict" | "none" | true;
|
|
95
|
+
}): ServerResponse {
|
|
96
|
+
return this.setHeader('Set-Cookie', COOKIE.serialize(name, String(value), options));
|
|
97
|
+
}
|
|
98
|
+
public async end({ status, headers, body }: {
|
|
99
|
+
body?: any;
|
|
100
|
+
status: number;
|
|
101
|
+
headers: OutgoingHttpHeaders;
|
|
102
|
+
}): Promise<void> {
|
|
103
|
+
return new Promise<void>((resolve, reject) => {
|
|
104
|
+
try {
|
|
105
|
+
this.res.statusCode = status;
|
|
106
|
+
const keys = Object.keys(headers);
|
|
107
|
+
for (const key of keys) {
|
|
108
|
+
if (headers[key] !== undefined) {
|
|
109
|
+
this.res.setHeader(key, headers[key] as any);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
this.res.end(body !== undefined ? String(body) : undefined, () => {
|
|
113
|
+
resolve();
|
|
114
|
+
});
|
|
115
|
+
} catch (e) {
|
|
116
|
+
reject(e);
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
121
|
+
public async json(body: any, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
|
|
122
|
+
return this.end({
|
|
123
|
+
status: status !== undefined ? status : 200,
|
|
124
|
+
headers: {
|
|
125
|
+
['Content-Type']: 'application/json; charset=utf-8',
|
|
126
|
+
...headers,
|
|
127
|
+
},
|
|
128
|
+
body: JSON.stringify(body)
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
public async text(text: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
|
|
132
|
+
return this.end({
|
|
133
|
+
status: status !== undefined ? status : 200,
|
|
134
|
+
headers: {
|
|
135
|
+
['Content-Type']: 'plain/text; charset=utf-8',
|
|
136
|
+
...headers
|
|
137
|
+
},
|
|
138
|
+
body: text
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
public async html(html: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
|
|
142
|
+
return this.end({
|
|
143
|
+
status: status !== undefined ? status : 200,
|
|
144
|
+
headers: {
|
|
145
|
+
['Content-Type']: 'text/html; charset=utf-8',
|
|
146
|
+
...headers
|
|
147
|
+
},
|
|
148
|
+
body: html
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
public async redirect(url: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
|
|
152
|
+
return this.end({
|
|
153
|
+
status: status !== undefined ? status : 302,
|
|
154
|
+
headers: {
|
|
155
|
+
['Location']: url,
|
|
156
|
+
...headers
|
|
157
|
+
}
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const newURL = (input: string, base?: string | any): any => {
|
|
2
|
+
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
|
3
|
+
// @ts-ignore
|
|
4
|
+
return new URL(input, base)
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export const newURLSearchParams = (arg?: string | any): any => {
|
|
8
|
+
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
|
9
|
+
// @ts-ignore
|
|
10
|
+
return new URLSearchParams(arg);
|
|
11
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { Router } from "./router";
|
|
2
|
+
import { Context, Handler } from "./context";
|
|
3
|
+
import { Method } from "./context";
|
|
4
|
+
import { matchTokenizePath, PathPartToken, tokenizePath } from "./tokenize-match";
|
|
5
|
+
|
|
6
|
+
export class RouterHandler {
|
|
7
|
+
|
|
8
|
+
private readonly tokens: PathPartToken[];
|
|
9
|
+
private readonly handler: Array<Handler | Handler | Router>;
|
|
10
|
+
private readonly isRouter: boolean;
|
|
11
|
+
|
|
12
|
+
public constructor(handler: Array<Handler> | Handler | Router, private readonly path: string | undefined, private readonly method: Method | undefined) {
|
|
13
|
+
this.tokens = tokenizePath(path);
|
|
14
|
+
this.handler = handler instanceof Array ? handler : [handler];
|
|
15
|
+
this.isRouter = handler instanceof Router;
|
|
16
|
+
if (!this.isRouter && this.handler.length !== this.handler.filter(h => typeof h === "function").length) {
|
|
17
|
+
throw new Error("bad arguments handler must be an array of Handler or a Router");
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
|
|
22
|
+
for (let i = 0; i < this.handler.length; i++) {
|
|
23
|
+
const h = this.handler[i];
|
|
24
|
+
if (h instanceof Router) {
|
|
25
|
+
if (!this.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
} else {
|
|
29
|
+
if (!this.pushResults(await h(ctx), ctx)) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
public isMatch(
|
|
38
|
+
method: string,
|
|
39
|
+
pathTokens: { value: string; lower: string; }[],
|
|
40
|
+
prePathTokens: PathPartToken[]): {
|
|
41
|
+
match: boolean;
|
|
42
|
+
params?: { [name: string]: string | undefined }
|
|
43
|
+
} {
|
|
44
|
+
if ((this.method === undefined || this.method === method)) {
|
|
45
|
+
if (this.path === undefined) {
|
|
46
|
+
return {
|
|
47
|
+
match: true
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
match: false
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private pushResults(shouldContinue: boolean, ctx: Context): boolean {
|
|
58
|
+
if (shouldContinue === false) {
|
|
59
|
+
// ctx.logger.debug(`avoiding next handlers because handler returned false.`);
|
|
60
|
+
return false;
|
|
61
|
+
} else if (shouldContinue !== true && shouldContinue !== undefined) {
|
|
62
|
+
ctx.logger.trace("pushing to results [%o]", shouldContinue);
|
|
63
|
+
ctx.results.push(shouldContinue);
|
|
64
|
+
}
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { Method, Handler, Context, ErrorHandler } from "./context";
|
|
2
|
+
import { RouterHandler } from "./router-utils";
|
|
3
|
+
import { normalizePath, PathPartToken, splitPath } from "./tokenize-match";
|
|
4
|
+
|
|
5
|
+
export class Router {
|
|
6
|
+
protected readonly handlers: RouterHandler[] = [];
|
|
7
|
+
protected readonly errorHandlers: ErrorHandler[] = [];
|
|
8
|
+
public get(path: string, handler: Array<Handler> | Handler | Router): Router {
|
|
9
|
+
return this.use(handler, path, "get");
|
|
10
|
+
}
|
|
11
|
+
public post(path: string, handler: Array<Handler> | Handler | Router): Router {
|
|
12
|
+
return this.use(handler, path, "post");
|
|
13
|
+
}
|
|
14
|
+
public patch(path: string, handler: Array<Handler> | Handler | Router): Router {
|
|
15
|
+
return this.use(handler, path, "patch");
|
|
16
|
+
}
|
|
17
|
+
public delete(path: string, handler: Array<Handler> | Handler | Router): Router {
|
|
18
|
+
return this.use(handler, path, "delete");
|
|
19
|
+
}
|
|
20
|
+
public put(path: string, handler: Array<Handler> | Handler | Router): Router {
|
|
21
|
+
return this.use(handler, path, "put");
|
|
22
|
+
}
|
|
23
|
+
public options(path: string, handler: Array<Handler> | Handler | Router): Router {
|
|
24
|
+
return this.use(handler, path, "options");
|
|
25
|
+
}
|
|
26
|
+
public use(handler: Array<Handler> | Handler | Router, path?: string, method?: Method): Router {
|
|
27
|
+
const nPath = path !== undefined ? normalizePath(path) : undefined;
|
|
28
|
+
const nMethod = method ? method.toUpperCase() as Method : method;
|
|
29
|
+
this.handlers.push(new RouterHandler(handler, nPath, nMethod));
|
|
30
|
+
return this;
|
|
31
|
+
}
|
|
32
|
+
public catch(errorHandler: Array<ErrorHandler> | ErrorHandler): Router {
|
|
33
|
+
const errorHandlers = errorHandler instanceof Array ? errorHandler : [errorHandler];
|
|
34
|
+
for (const e of errorHandlers) {
|
|
35
|
+
this.errorHandlers.push(e);
|
|
36
|
+
}
|
|
37
|
+
return this;
|
|
38
|
+
}
|
|
39
|
+
public async run(ctx: Context, pathTokens?: { value: string; lower: string; }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
|
|
40
|
+
pathTokens = pathTokens ? pathTokens : splitPath(ctx.path);
|
|
41
|
+
try {
|
|
42
|
+
let shouldContinue = true;
|
|
43
|
+
for (const h of this.handlers) {
|
|
44
|
+
if (!shouldContinue || ctx.res.headersSent) {
|
|
45
|
+
shouldContinue = false;
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
const isMatch = h.isMatch(ctx.method, pathTokens, prePathTokens);
|
|
49
|
+
if (isMatch.match) {
|
|
50
|
+
if (isMatch.params) {
|
|
51
|
+
ctx.params = ctx.params ? {
|
|
52
|
+
...ctx.params,
|
|
53
|
+
...isMatch.params
|
|
54
|
+
} : isMatch.params;
|
|
55
|
+
}
|
|
56
|
+
shouldContinue = await h.invoke(ctx, pathTokens, prePathTokens);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return !ctx.res.headersSent;
|
|
60
|
+
} catch (e: any) {
|
|
61
|
+
for (const eH of this.errorHandlers) {
|
|
62
|
+
const ret = await eH(e, ctx);
|
|
63
|
+
if (ret === false || ctx.res.headersSent) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
throw e; // pass the error along
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { URLSearchParams } from "url";
|
|
2
|
+
import { newURLSearchParams } from "./helpers";
|
|
3
|
+
|
|
4
|
+
export const parseSearchParams = (search: URLSearchParams): { [name: string]: string | string[] } => {
|
|
5
|
+
const query: { [name: string]: string | string[] } = {};
|
|
6
|
+
search.forEach((value: string, key: string) => {
|
|
7
|
+
query[key] = query[key] instanceof Array ? (query[key] as string[]).concat([value]) : query[key] ? [query[key] as string, value] : value;
|
|
8
|
+
});
|
|
9
|
+
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
|
+
};
|
|
39
|
+
|
|
40
|
+
// adds "/" to the final of path
|
|
41
|
+
// cannot account for query or hash params so send only new URL().pathname
|
|
42
|
+
export const normalizePath = (path: string): string => {
|
|
43
|
+
if (typeof path !== "string") {
|
|
44
|
+
throw new Error("path not string");
|
|
45
|
+
}
|
|
46
|
+
if (path.length > 1) {
|
|
47
|
+
if (path.charAt(0) !== "/") {
|
|
48
|
+
throw new Error("path doesnt start with /");
|
|
49
|
+
}
|
|
50
|
+
if (path[path.length - 1] !== "/") {
|
|
51
|
+
return `${path}/`;
|
|
52
|
+
} else {
|
|
53
|
+
return path; // already normalized
|
|
54
|
+
}
|
|
55
|
+
} else if (path !== "/") {
|
|
56
|
+
throw new Error("path of length 1 not /");
|
|
57
|
+
} else {
|
|
58
|
+
return path; // "/"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface PathPartToken {
|
|
63
|
+
optional: boolean;
|
|
64
|
+
wild?: string;
|
|
65
|
+
token: string;
|
|
66
|
+
lower: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export const pathPartTokenize = (token: { value: string; lower: string; }): PathPartToken => {
|
|
70
|
+
const isWild = token.value[0] === ":";
|
|
71
|
+
const optional = token.value[token.value.length - 1] === "?";
|
|
72
|
+
const wild = isWild ? token.value.substring(1, token.value.length - (optional ? 1 : 0)) : undefined;
|
|
73
|
+
return {
|
|
74
|
+
optional,
|
|
75
|
+
wild,
|
|
76
|
+
token: token.value,
|
|
77
|
+
lower: token.lower
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export const splitPath = (path?: string): { value: string; lower: string; }[] => path === undefined ? [] : path.split("/").filter(p => p).map(p => {
|
|
82
|
+
return {
|
|
83
|
+
value: p,
|
|
84
|
+
lower: p.toLocaleLowerCase()
|
|
85
|
+
};
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
export const tokenizePath = (path?: string): PathPartToken[] => {
|
|
89
|
+
if (path === undefined) {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
const tokens = splitPath(path).map(token => pathPartTokenize(token));
|
|
93
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
94
|
+
if (tokens[i].optional && i != tokens.length - 1) {
|
|
95
|
+
throw new Error("cannot set a path token as optional that's not the last one");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return tokens;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export const matchTokenizePath = (checkAsRouter: boolean, tokens: PathPartToken[], ctxTokens: { value: string; lower: string; }[]): {
|
|
102
|
+
match: boolean;
|
|
103
|
+
params?: { [name: string]: string | undefined }
|
|
104
|
+
} => {
|
|
105
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
106
|
+
if (tokens[i].optional && i != tokens.length - 1) {
|
|
107
|
+
throw new Error("cannot set a path token as optional that's not the last one");
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const lastTokenIsOptional = tokens.length > 0 ? tokens[tokens.length - 1].optional : false;
|
|
111
|
+
const couldBeUsingOptional = (lastTokenIsOptional &&
|
|
112
|
+
(
|
|
113
|
+
(!checkAsRouter && tokens.length - 1 === ctxTokens.length) ||
|
|
114
|
+
(checkAsRouter && tokens.length - 1 <= ctxTokens.length)
|
|
115
|
+
)
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
const params: { [name: string]: string | undefined } = {};
|
|
119
|
+
|
|
120
|
+
if ((!checkAsRouter && tokens.length === ctxTokens.length) || couldBeUsingOptional || (checkAsRouter && tokens.length <= ctxTokens.length)) {
|
|
121
|
+
// similiar count of tokens
|
|
122
|
+
for (let i = 0; i < ctxTokens.length; i++) {
|
|
123
|
+
const ctxToken = ctxTokens[i];
|
|
124
|
+
if (checkAsRouter && i >= tokens.length) {
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (tokens[i].wild || ctxToken.lower === tokens[i].lower) {
|
|
129
|
+
// check pass
|
|
130
|
+
const wild = tokens[i].wild;
|
|
131
|
+
if (wild) {
|
|
132
|
+
params[wild] = ctxToken.value;
|
|
133
|
+
}
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
match: false,
|
|
139
|
+
params: {}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
match: true,
|
|
144
|
+
params
|
|
145
|
+
};
|
|
146
|
+
} else {
|
|
147
|
+
return {
|
|
148
|
+
match: false,
|
|
149
|
+
params: {}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
}
|