@miqro/core 1.7.0 → 1.7.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/dist/api-router.js +0 -1
- package/dist/app-utils.js +0 -1
- package/dist/app.js +2 -3
- package/dist/common/api-router-utils.js +0 -1
- package/dist/common/api-router.js +0 -1
- package/dist/common/config/config.js +0 -1
- package/dist/common/config/featuretoggle.js +0 -1
- package/dist/common/config/index.js +0 -1
- package/dist/common/config/loader.js +0 -1
- package/dist/common/context.d.ts +2 -1
- package/dist/common/context.js +27 -12
- package/dist/common/error/badrequesterror.js +0 -1
- package/dist/common/error/configfilenotfound.js +0 -1
- package/dist/common/error/forbiddenerror.js +0 -1
- package/dist/common/error/index.js +0 -1
- package/dist/common/error/notfound.js +0 -1
- package/dist/common/error/notimplemented.js +0 -1
- package/dist/common/error/unauthorizederror.js +0 -1
- package/dist/common/helpers.js +0 -1
- package/dist/common/index.js +0 -1
- package/dist/common/logger/constants.js +0 -1
- package/dist/common/logger/factory.js +0 -1
- package/dist/common/logger/index.js +0 -1
- package/dist/common/logger/interfaces.js +0 -1
- package/dist/common/logger/logger.js +0 -1
- package/dist/common/logger/transport/console.js +0 -1
- package/dist/common/logger/transport/file.js +0 -1
- package/dist/common/router-handler.js +0 -1
- package/dist/common/router-helpers.js +0 -1
- package/dist/common/router-utils.js +0 -1
- package/dist/common/session/common.js +0 -1
- package/dist/common/session/index.js +0 -1
- package/dist/common/session/service.js +0 -1
- package/dist/common/tokenize-match.js +0 -1
- package/dist/index.js +0 -1
- package/dist/middleware/buffer.js +0 -1
- package/dist/middleware/cookie.js +0 -1
- package/dist/middleware/cors.js +0 -1
- package/dist/middleware/form.js +0 -1
- package/dist/middleware/group.js +0 -1
- package/dist/middleware/index.js +0 -1
- package/dist/middleware/json.js +0 -1
- package/dist/middleware/logger.js +0 -1
- package/dist/middleware/parse.js +0 -1
- package/dist/middleware/result.js +0 -1
- package/dist/middleware/session.js +0 -1
- package/dist/middleware/tag.js +0 -1
- package/dist/middleware/text.js +0 -1
- package/dist/proxy.js +28 -11
- package/dist/router.js +2 -3
- package/dist/static.js +0 -1
- package/package.json +7 -9
- package/dist/api-router.js.map +0 -1
- package/dist/app-utils.js.map +0 -1
- package/dist/app.js.map +0 -1
- package/dist/common/api-router-utils.js.map +0 -1
- package/dist/common/api-router.js.map +0 -1
- package/dist/common/config/config.js.map +0 -1
- package/dist/common/config/featuretoggle.js.map +0 -1
- package/dist/common/config/index.js.map +0 -1
- package/dist/common/config/loader.js.map +0 -1
- package/dist/common/context.js.map +0 -1
- package/dist/common/error/badrequesterror.js.map +0 -1
- package/dist/common/error/configfilenotfound.js.map +0 -1
- package/dist/common/error/forbiddenerror.js.map +0 -1
- package/dist/common/error/index.js.map +0 -1
- package/dist/common/error/notfound.js.map +0 -1
- package/dist/common/error/notimplemented.js.map +0 -1
- package/dist/common/error/unauthorizederror.js.map +0 -1
- package/dist/common/helpers.js.map +0 -1
- package/dist/common/index.js.map +0 -1
- package/dist/common/logger/constants.js.map +0 -1
- package/dist/common/logger/factory.js.map +0 -1
- package/dist/common/logger/index.js.map +0 -1
- package/dist/common/logger/interfaces.js.map +0 -1
- package/dist/common/logger/logger.js.map +0 -1
- package/dist/common/logger/transport/console.js.map +0 -1
- package/dist/common/logger/transport/file.js.map +0 -1
- package/dist/common/router-handler.js.map +0 -1
- package/dist/common/router-helpers.js.map +0 -1
- package/dist/common/router-utils.js.map +0 -1
- package/dist/common/session/common.js.map +0 -1
- package/dist/common/session/index.js.map +0 -1
- package/dist/common/session/service.js.map +0 -1
- package/dist/common/tokenize-match.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/middleware/buffer.js.map +0 -1
- package/dist/middleware/cookie.js.map +0 -1
- package/dist/middleware/cors.js.map +0 -1
- package/dist/middleware/form.js.map +0 -1
- package/dist/middleware/group.js.map +0 -1
- package/dist/middleware/index.js.map +0 -1
- package/dist/middleware/json.js.map +0 -1
- package/dist/middleware/logger.js.map +0 -1
- package/dist/middleware/parse.js.map +0 -1
- package/dist/middleware/result.js.map +0 -1
- package/dist/middleware/session.js.map +0 -1
- package/dist/middleware/tag.js.map +0 -1
- package/dist/middleware/text.js.map +0 -1
- package/dist/proxy.js.map +0 -1
- package/dist/router.js.map +0 -1
- package/dist/static.js.map +0 -1
- package/src/api-router.ts +0 -60
- package/src/api-router.unit.test.js +0 -273
- package/src/app-utils.ts +0 -82
- package/src/app-utils.unit.test.js +0 -100
- package/src/app.ts +0 -51
- package/src/app.unit.test.js +0 -334
- package/src/common/api-router-utils.ts +0 -193
- package/src/common/api-router.ts +0 -19
- package/src/common/config/config.ts +0 -111
- package/src/common/config/featuretoggle.ts +0 -6
- package/src/common/config/index.ts +0 -3
- package/src/common/config/loader.ts +0 -80
- package/src/common/context.ts +0 -167
- package/src/common/context.unit.test.js +0 -288
- 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/index.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/helpers.ts +0 -11
- package/src/common/index.ts +0 -7
- package/src/common/logger/constants.ts +0 -27
- package/src/common/logger/factory.ts +0 -53
- package/src/common/logger/index.ts +0 -6
- package/src/common/logger/interfaces.ts +0 -19
- package/src/common/logger/logger.ts +0 -136
- package/src/common/logger/transport/console.ts +0 -34
- package/src/common/logger/transport/file.ts +0 -26
- package/src/common/router-handler.ts +0 -159
- package/src/common/router-helpers.ts +0 -20
- package/src/common/router-utils.ts +0 -95
- package/src/common/session/common.ts +0 -40
- package/src/common/session/index.ts +0 -2
- package/src/common/session/service.ts +0 -160
- package/src/common/tokenize-match.ts +0 -130
- package/src/index.ts +0 -7
- package/src/middleware/buffer.ts +0 -80
- package/src/middleware/cookie.ts +0 -20
- package/src/middleware/cors.ts +0 -96
- package/src/middleware/form.ts +0 -59
- package/src/middleware/group.ts +0 -70
- package/src/middleware/index.ts +0 -48
- package/src/middleware/json.ts +0 -55
- package/src/middleware/logger.ts +0 -18
- package/src/middleware/parse.ts +0 -93
- package/src/middleware/result.ts +0 -43
- package/src/middleware/session.ts +0 -136
- package/src/middleware/tag.ts +0 -15
- package/src/middleware/text.ts +0 -45
- package/src/proxy.ts +0 -77
- package/src/proxy.unit.test.js +0 -159
- package/src/router.ts +0 -112
- package/src/router.unit.test.js +0 -397
- package/src/setup-test.js +0 -5
- package/src/static.ts +0 -238
|
@@ -1,136 +0,0 @@
|
|
|
1
|
-
import {checkEnvVariables, Context, ForbiddenError, Handler, SessionHandlerOptions, UnAuthorizedError} from "../common";
|
|
2
|
-
import {parse} from "@miqro/parser";
|
|
3
|
-
|
|
4
|
-
const DEFAULT_TOKEN_LOCATION = "header";
|
|
5
|
-
const DEFAULT_TOKEN_HEADER = "Authorization";
|
|
6
|
-
const DEFAULT_TOKEN_QUERY = "token";
|
|
7
|
-
const DEFAULT_TOKEN_COOKIE = "Authorization";
|
|
8
|
-
const DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY = "true";
|
|
9
|
-
const DEFAULT_TOKEN_SET_COOKIE_SECURE = "true";
|
|
10
|
-
const DEFAULT_TOKEN_SET_COOKIE_PATH = "/";
|
|
11
|
-
const DEFAULT_TOKEN_SET_COOKIE_SAME_SITE = "strict";
|
|
12
|
-
|
|
13
|
-
export const SessionHandler = (config: SessionHandlerOptions): Handler<void> => {
|
|
14
|
-
if (!config.options) {
|
|
15
|
-
const tokenLocation = checkEnvVariables(["TOKEN_LOCATION"], [DEFAULT_TOKEN_LOCATION])[0];
|
|
16
|
-
config.options = {
|
|
17
|
-
tokenLocation: tokenLocation as any,
|
|
18
|
-
tokenLocationName: "",
|
|
19
|
-
setCookieOptions: {
|
|
20
|
-
httpOnly: true,
|
|
21
|
-
path: "/",
|
|
22
|
-
sameSite: "strict",
|
|
23
|
-
secure: true
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
switch (tokenLocation) {
|
|
27
|
-
case "header":
|
|
28
|
-
config.options.tokenLocationName = checkEnvVariables(["TOKEN_HEADER"], [DEFAULT_TOKEN_HEADER])[0];
|
|
29
|
-
break;
|
|
30
|
-
case "query":
|
|
31
|
-
config.options.tokenLocationName = checkEnvVariables(["TOKEN_QUERY"], [DEFAULT_TOKEN_QUERY])[0];
|
|
32
|
-
break;
|
|
33
|
-
case "cookie":
|
|
34
|
-
config.options.tokenLocationName = checkEnvVariables(["TOKEN_COOKIE"], [DEFAULT_TOKEN_COOKIE])[0];
|
|
35
|
-
const [httpOnlyS, secureS, path, sameSite] = checkEnvVariables(
|
|
36
|
-
["TOKEN_SET_COOKIE_HTTP_ONLY", "TOKEN_SET_COOKIE_SECURE", "TOKEN_SET_COOKIE_PATH", "TOKEN_SET_COOKIE_SAME_SITE"],
|
|
37
|
-
[DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY, DEFAULT_TOKEN_SET_COOKIE_SECURE, DEFAULT_TOKEN_SET_COOKIE_PATH, DEFAULT_TOKEN_SET_COOKIE_SAME_SITE]);
|
|
38
|
-
config.options.setCookieOptions = {
|
|
39
|
-
httpOnly: httpOnlyS === "true",
|
|
40
|
-
secure: secureS === "true",
|
|
41
|
-
path,
|
|
42
|
-
sameSite: sameSite as any
|
|
43
|
-
};
|
|
44
|
-
break;
|
|
45
|
-
default:
|
|
46
|
-
throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header or query)`);
|
|
47
|
-
}
|
|
48
|
-
} else {
|
|
49
|
-
config.options = parse(config.options as any, [
|
|
50
|
-
{name: "tokenLocation", required: true, type: "enum", enumValues: ["header", "query", "cookie"]},
|
|
51
|
-
{name: "tokenLocationName", required: true, type: "any"},
|
|
52
|
-
{
|
|
53
|
-
name: "setCookieOptions", required: false, type: "nested", defaultValue: {
|
|
54
|
-
httpOnly: DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY === "true",
|
|
55
|
-
secure: DEFAULT_TOKEN_SET_COOKIE_SECURE === "true",
|
|
56
|
-
path: DEFAULT_TOKEN_SET_COOKIE_PATH,
|
|
57
|
-
sameSite: DEFAULT_TOKEN_SET_COOKIE_SAME_SITE,
|
|
58
|
-
}, nestedOptions: {
|
|
59
|
-
mode: "no_extra",
|
|
60
|
-
options: [
|
|
61
|
-
{name: "httpOnly", required: true, type: "boolean"},
|
|
62
|
-
{name: "secure", required: true, type: "boolean"},
|
|
63
|
-
{name: "path", required: true, type: "any"},
|
|
64
|
-
{name: "sameSite", required: true, type: "enum", enumValues: ["lax", "strict", "none"]}
|
|
65
|
-
]
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
], "no_extra", "options") as any;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
if (!config.authService) {
|
|
72
|
-
throw new Error("authService must be provided!");
|
|
73
|
-
}
|
|
74
|
-
if (!config.options || !config.options.setCookieOptions) {
|
|
75
|
-
throw new Error("config.options not populated!");
|
|
76
|
-
}
|
|
77
|
-
const tokenLocation = config.options.tokenLocation;
|
|
78
|
-
const tokenLocationName = config.options.tokenLocationName;
|
|
79
|
-
const setCookieOptions = config.options.setCookieOptions;
|
|
80
|
-
return async function SessionHandler(ctx: Context): Promise<void> {
|
|
81
|
-
try {
|
|
82
|
-
const tlN = typeof tokenLocationName === "string" ? tokenLocationName : await tokenLocationName(ctx);
|
|
83
|
-
let token = null;
|
|
84
|
-
switch (tokenLocation) {
|
|
85
|
-
case "header":
|
|
86
|
-
token = ctx.headers[(tlN).toLowerCase()] as string;
|
|
87
|
-
break;
|
|
88
|
-
case "query":
|
|
89
|
-
token = ctx.query[tlN] as string;
|
|
90
|
-
break;
|
|
91
|
-
case "cookie":
|
|
92
|
-
token = ctx.cookies[tlN] ? ctx.cookies[tlN] : undefined;
|
|
93
|
-
break;
|
|
94
|
-
default:
|
|
95
|
-
throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header, query or cookie)`);
|
|
96
|
-
}
|
|
97
|
-
if (!token) {
|
|
98
|
-
ctx.logger.warn("No token provided!");
|
|
99
|
-
throw new ForbiddenError("NO TOKEN");
|
|
100
|
-
} else {
|
|
101
|
-
const session = await config.authService.verify({token, ctx});
|
|
102
|
-
if (!session) {
|
|
103
|
-
ctx.logger.warn("fail to authenticate token [%s]!", token);
|
|
104
|
-
throw new UnAuthorizedError();
|
|
105
|
-
} else {
|
|
106
|
-
if (tokenLocation === "cookie" && session.token !== token) {
|
|
107
|
-
const newTokenCookie = String(session.token ? session.token : token);
|
|
108
|
-
const cookiePath = typeof setCookieOptions.path === "string" ? setCookieOptions.path : await setCookieOptions.path(ctx);
|
|
109
|
-
ctx.setCookie(tlN, newTokenCookie, session.expires instanceof Date ? {
|
|
110
|
-
httpOnly: setCookieOptions.httpOnly,
|
|
111
|
-
secure: setCookieOptions.secure,
|
|
112
|
-
path: cookiePath,
|
|
113
|
-
sameSite: setCookieOptions.sameSite,
|
|
114
|
-
expires: session.expires
|
|
115
|
-
} : {
|
|
116
|
-
httpOnly: setCookieOptions.httpOnly,
|
|
117
|
-
path: cookiePath,
|
|
118
|
-
secure: setCookieOptions.secure,
|
|
119
|
-
sameSite: setCookieOptions.sameSite
|
|
120
|
-
})
|
|
121
|
-
}
|
|
122
|
-
ctx.session = session;
|
|
123
|
-
ctx.logger.debug("authenticated!");
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
} catch (e: any) {
|
|
127
|
-
if (e.message && e.message === "NO TOKEN") {
|
|
128
|
-
throw e;
|
|
129
|
-
} else {
|
|
130
|
-
throw new UnAuthorizedError();
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
};
|
|
134
|
-
};
|
|
135
|
-
|
|
136
|
-
|
package/src/middleware/tag.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import {Context, Handler} from "../common";
|
|
2
|
-
|
|
3
|
-
export const TagResponse = (options?: {
|
|
4
|
-
uuid?: boolean;
|
|
5
|
-
}): Handler<void> =>
|
|
6
|
-
function TagResponse(ctx: Context): void {
|
|
7
|
-
if (options && options.uuid) {
|
|
8
|
-
ctx.setHeader("uuid", ctx.uuid);
|
|
9
|
-
}
|
|
10
|
-
const requestUUID = ctx.headers['request-uuid'];
|
|
11
|
-
if (requestUUID) {
|
|
12
|
-
ctx.setHeader("request-uuid", requestUUID);
|
|
13
|
-
}
|
|
14
|
-
};
|
|
15
|
-
|
package/src/middleware/text.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import {BadRequestError, checkEnvVariables, Context, Handler} from "../common";
|
|
2
|
-
import {DEFAULT_READ_BUFFER_LIMIT, ReadBuffer} from "./buffer";
|
|
3
|
-
|
|
4
|
-
export const TextParser = (options?: {
|
|
5
|
-
limit?: number;
|
|
6
|
-
type?: string;
|
|
7
|
-
}): Handler<void> => {
|
|
8
|
-
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
9
|
-
let type = "plain/text";
|
|
10
|
-
if (options) {
|
|
11
|
-
limit = options.limit !== undefined ? options.limit : limit;
|
|
12
|
-
type = options.type !== undefined ? options.type : type;
|
|
13
|
-
} else {
|
|
14
|
-
const [limitS, typeS] =
|
|
15
|
-
checkEnvVariables(["BODY_TEXT_PARSER_LIMIT", "BODY_TEXT_PARSER_TYPE"], [String(DEFAULT_READ_BUFFER_LIMIT), "plain/text"]);
|
|
16
|
-
limit = parseInt(limitS, 10);
|
|
17
|
-
type = typeS;
|
|
18
|
-
}
|
|
19
|
-
const readBuffer = ReadBuffer({
|
|
20
|
-
limit
|
|
21
|
-
});
|
|
22
|
-
return async function TextParser(ctx: Context): Promise<void> {
|
|
23
|
-
try {
|
|
24
|
-
const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
|
|
25
|
-
if (isType && !ctx.buffer) {
|
|
26
|
-
await readBuffer(ctx);
|
|
27
|
-
}
|
|
28
|
-
if (isType && ctx.buffer && ctx.buffer.length <= limit) {
|
|
29
|
-
const string = ctx.buffer.toString();
|
|
30
|
-
ctx.logger.debug("ctx.body = %s", string);
|
|
31
|
-
ctx.body = string;
|
|
32
|
-
} else if (isType && ctx.buffer && ctx.buffer.length > limit) {
|
|
33
|
-
ctx.logger.error(`ctx.buffer.length ${ctx.buffer.length} > ${limit}. To accept this body set BODY_TEXT_PARSER_LIMIT to a higher value.`);
|
|
34
|
-
throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
|
|
35
|
-
}
|
|
36
|
-
} catch (e: any) {
|
|
37
|
-
if (e && e.name === "BadRequestError") {
|
|
38
|
-
throw e;
|
|
39
|
-
} else {
|
|
40
|
-
ctx.logger.error(e);
|
|
41
|
-
throw new BadRequestError();
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
};
|
|
45
|
-
};
|
package/src/proxy.ts
DELETED
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import {Context} from "./common";
|
|
2
|
-
import {request, RequestOptions} from "@miqro/request";
|
|
3
|
-
import {Router, RouterOptions} from "./router";
|
|
4
|
-
import {normalizePath, PathPartToken} from "./common/tokenize-match";
|
|
5
|
-
import {URL} from "url";
|
|
6
|
-
|
|
7
|
-
export interface ProxyRouterOptions extends RouterOptions {
|
|
8
|
-
url: string;
|
|
9
|
-
rejectUnauthorized?: boolean;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
class ProxyRouter extends Router {
|
|
13
|
-
private readonly proxyURL: URL;
|
|
14
|
-
private readonly rejectUnauthorized?: boolean;
|
|
15
|
-
|
|
16
|
-
constructor(options: ProxyRouterOptions) {
|
|
17
|
-
super(options);
|
|
18
|
-
const proxyURL = new URL(options.url);
|
|
19
|
-
proxyURL.pathname = normalizePath(proxyURL.pathname);
|
|
20
|
-
this.proxyURL = proxyURL;
|
|
21
|
-
this.rejectUnauthorized = options.rejectUnauthorized;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
async run(ctx: Context, pathTokens?: { value: string; lower: string }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
|
|
25
|
-
|
|
26
|
-
const level = prePathTokens.length;
|
|
27
|
-
const shouldContinue = await super.run(ctx, pathTokens, prePathTokens);
|
|
28
|
-
|
|
29
|
-
if (shouldContinue) {
|
|
30
|
-
const relative = ctx.path.split("/").map(s => s.trim()).filter(s => s).slice(level).join("/");
|
|
31
|
-
|
|
32
|
-
const nUrl = new URL(this.proxyURL.toString());
|
|
33
|
-
nUrl.pathname = nUrl.pathname + relative;
|
|
34
|
-
const url = nUrl.toString();
|
|
35
|
-
|
|
36
|
-
const headers = {
|
|
37
|
-
...ctx.headers
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
delete headers["connection"];
|
|
41
|
-
delete headers["keep-alive"];
|
|
42
|
-
|
|
43
|
-
const requestArgs: RequestOptions = {
|
|
44
|
-
url: url.toString(),
|
|
45
|
-
query: ctx.query,
|
|
46
|
-
disableThrow: true,
|
|
47
|
-
rejectUnauthorized: this.rejectUnauthorized,
|
|
48
|
-
disableUserAgent: true,
|
|
49
|
-
method: ctx.method,
|
|
50
|
-
headers,
|
|
51
|
-
data: ctx.method !== "GET" ? ctx.buffer : undefined
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
ctx.logger.info("proxy to %s", url.toString());
|
|
55
|
-
ctx.logger.debug("proxy with %o", requestArgs);
|
|
56
|
-
|
|
57
|
-
const response = await request(requestArgs);
|
|
58
|
-
|
|
59
|
-
const responseHeaders = {
|
|
60
|
-
...response.headers
|
|
61
|
-
};
|
|
62
|
-
delete responseHeaders["connection"];
|
|
63
|
-
delete responseHeaders["keep-alive"];
|
|
64
|
-
|
|
65
|
-
await ctx.end({
|
|
66
|
-
headers: responseHeaders,
|
|
67
|
-
body: response.buffer,
|
|
68
|
-
status: response.status
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
return !ctx.res.headersSent;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export const Proxy = (options: ProxyRouterOptions) => {
|
|
76
|
-
return new ProxyRouter(options);
|
|
77
|
-
}
|
package/src/proxy.unit.test.js
DELETED
|
@@ -1,159 +0,0 @@
|
|
|
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
|
-
debug: fake(() => {
|
|
88
|
-
|
|
89
|
-
})
|
|
90
|
-
},
|
|
91
|
-
end: fake(()=>{
|
|
92
|
-
|
|
93
|
-
})
|
|
94
|
-
}
|
|
95
|
-
}].forEach(({context}) => {
|
|
96
|
-
it("this.run: super.run returns true with options " + JSON.stringify(fakeOptions) + " and context " + context.path, async () => {
|
|
97
|
-
const routerCtr = fake(() => {
|
|
98
|
-
|
|
99
|
-
});
|
|
100
|
-
const routerRun = fake(async () => {
|
|
101
|
-
return true;
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
const normalizePathRet = "normalizePathRet";
|
|
105
|
-
|
|
106
|
-
const urlCtr = fake(() => {
|
|
107
|
-
return "fakePath";
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
class Router {
|
|
111
|
-
constructor(options) {
|
|
112
|
-
routerCtr(options);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
run() {
|
|
116
|
-
return routerRun(...arguments);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
class URL {
|
|
121
|
-
constructor(options) {
|
|
122
|
-
this.pathname = urlCtr(options);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
const normalizePath = fake((args) => {
|
|
127
|
-
return normalizePathRet;
|
|
128
|
-
});
|
|
129
|
-
const requestRet = {
|
|
130
|
-
|
|
131
|
-
};
|
|
132
|
-
const request = fake(async () => {
|
|
133
|
-
return requestRet;
|
|
134
|
-
});
|
|
135
|
-
|
|
136
|
-
const {Proxy} = requireMock(testFilePath, {
|
|
137
|
-
"./common": {},
|
|
138
|
-
"@miqro/request": {
|
|
139
|
-
request
|
|
140
|
-
},
|
|
141
|
-
"./router": {
|
|
142
|
-
Router
|
|
143
|
-
},
|
|
144
|
-
"./common/tokenize-match": {
|
|
145
|
-
normalizePath
|
|
146
|
-
},
|
|
147
|
-
"url": {
|
|
148
|
-
URL
|
|
149
|
-
},
|
|
150
|
-
}, basePath);
|
|
151
|
-
//console.dir(Object.keys(require.cache))
|
|
152
|
-
const router = Proxy(fakeOptions);
|
|
153
|
-
const ret = await router.run(context);
|
|
154
|
-
strictEqual(request.callCount, 1);
|
|
155
|
-
// TODO assert path
|
|
156
|
-
});
|
|
157
|
-
});
|
|
158
|
-
});
|
|
159
|
-
});
|
package/src/router.ts
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
import {IncomingMessage, RequestListener} from "http";
|
|
2
|
-
import {v4} from "uuid";
|
|
3
|
-
import {Logger} from "./common/logger/index.js";
|
|
4
|
-
import {Context, ErrorHandler, Handler, Method} from "./common/context";
|
|
5
|
-
import {HandlerWithOptions, RouterHandlerOptions, RouterJSONDoc} from "./common/router-utils";
|
|
6
|
-
import {normalizePath, PathPart, PathPartToken, splitPath} from "./common/tokenize-match";
|
|
7
|
-
import {defaultLoggerFactory} from "./common/router-helpers";
|
|
8
|
-
import {RouterHandler} from "./common/router-handler";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
export interface RouterOptions {
|
|
12
|
-
loggerFactory?: (uuid: string, req: IncomingMessage) => Logger;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export class Router {
|
|
16
|
-
protected readonly handlers: RouterHandler[] = [];
|
|
17
|
-
protected readonly errorHandlers: ErrorHandler[] = [];
|
|
18
|
-
public readonly listener: RequestListener;
|
|
19
|
-
|
|
20
|
-
constructor(protected config?: RouterOptions) {
|
|
21
|
-
const loggerFactory = this.config && this.config.loggerFactory ? this.config.loggerFactory : defaultLoggerFactory;
|
|
22
|
-
this.listener = async (req, res) => {
|
|
23
|
-
const uuid = v4().toString();
|
|
24
|
-
const logger = loggerFactory(uuid, req);
|
|
25
|
-
const ctx = new Context(uuid, req, res, logger);
|
|
26
|
-
ctx.logger.trace(`request received`);
|
|
27
|
-
await this.run(ctx);
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
public get(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
32
|
-
return this.use(handler, path, "get", options);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
public post(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
36
|
-
return this.use(handler, path, "post", options);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
public patch(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
40
|
-
return this.use(handler, path, "patch", options);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
public delete(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
44
|
-
return this.use(handler, path, "delete", options);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
public put(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
48
|
-
return this.use(handler, path, "put", options);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
public options(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
52
|
-
return this.use(handler, path, "options", options);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
public use(handler: Array<Handler> | HandlerWithOptions | Handler | Router, path?: string, method?: Method, options?: RouterHandlerOptions): Router {
|
|
56
|
-
const nPath = path !== undefined ? normalizePath(path) : undefined;
|
|
57
|
-
const nMethod = method ? method.toUpperCase() as Method : method;
|
|
58
|
-
this.handlers.push(new RouterHandler(handler, nPath, nMethod, options));
|
|
59
|
-
return this;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
public catch(errorHandler: Array<ErrorHandler> | ErrorHandler): Router {
|
|
63
|
-
const errorHandlers = errorHandler instanceof Array ? errorHandler : [errorHandler];
|
|
64
|
-
for (const e of errorHandlers) {
|
|
65
|
-
if (typeof e !== "function") {
|
|
66
|
-
throw new Error(`errorHandler ${e} not a function!`);
|
|
67
|
-
}
|
|
68
|
-
this.errorHandlers.push(e);
|
|
69
|
-
}
|
|
70
|
-
return this;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
public async run(ctx: Context, pathTokens?: PathPart[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
|
|
74
|
-
pathTokens = pathTokens ? pathTokens : splitPath(ctx.path);
|
|
75
|
-
try {
|
|
76
|
-
for (const h of this.handlers) {
|
|
77
|
-
if (ctx.res.headersSent) {
|
|
78
|
-
break;
|
|
79
|
-
}
|
|
80
|
-
const isMatch = h.isMatch(ctx.method, pathTokens, prePathTokens);
|
|
81
|
-
if (isMatch.match) {
|
|
82
|
-
if (isMatch.params) {
|
|
83
|
-
ctx.params = ctx.params ? {
|
|
84
|
-
...ctx.params,
|
|
85
|
-
...isMatch.params
|
|
86
|
-
} : isMatch.params;
|
|
87
|
-
}
|
|
88
|
-
const shouldContinue = await h.invoke(ctx, pathTokens, prePathTokens);
|
|
89
|
-
if (!shouldContinue) {
|
|
90
|
-
break;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
return !ctx.res.headersSent;
|
|
95
|
-
} catch (e: any) {
|
|
96
|
-
for (const eH of this.errorHandlers) {
|
|
97
|
-
const ret = await eH(e, ctx);
|
|
98
|
-
if (ret === false || ctx.res.headersSent) {
|
|
99
|
-
return false;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
throw e; // pass the error along
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
|
|
107
|
-
for (const h of this.handlers) {
|
|
108
|
-
doc = h.getJSONDoc(doc, prePath);
|
|
109
|
-
}
|
|
110
|
-
return doc;
|
|
111
|
-
}
|
|
112
|
-
}
|