@miqro/core 1.5.9 → 1.5.10
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/package.json +4 -4
- package/src/api-router.ts +51 -0
- package/src/app.ts +136 -0
- package/src/common/api-router-helpers.ts +32 -0
- package/src/common/api-router-utils.ts +206 -0
- package/src/common/config/config.ts +99 -0
- package/src/common/config/featuretoggle.ts +6 -0
- package/src/common/config/index.ts +3 -0
- package/src/common/config/loader.ts +80 -0
- package/src/common/context.ts +156 -0
- package/src/common/error/badrequesterror.ts +6 -0
- package/src/common/error/configfilenotfound.ts +6 -0
- package/src/common/error/forbiddenerror.ts +6 -0
- package/src/common/error/index.ts +6 -0
- package/src/common/error/notfound.ts +6 -0
- package/src/common/error/notimplemented.ts +6 -0
- package/src/common/error/unauthorizederror.ts +6 -0
- package/src/common/helpers.ts +11 -0
- package/src/common/index.ts +7 -0
- package/src/common/logger/common.ts +6 -0
- package/src/common/logger/factory.ts +51 -0
- package/src/common/logger/formatter.ts +9 -0
- package/src/common/logger/index.ts +6 -0
- package/src/common/logger/logger.ts +114 -0
- package/src/common/logger/transport.ts +71 -0
- package/src/common/router-helpers.ts +20 -0
- package/src/common/router-utils.ts +93 -0
- package/src/common/session/common.ts +37 -0
- package/src/common/session/index.ts +2 -0
- package/src/common/session/service.ts +157 -0
- package/src/common/tokenize-match.ts +152 -0
- package/src/index.ts +7 -0
- package/src/middleware/buffer.ts +80 -0
- package/src/middleware/cookie.ts +20 -0
- package/src/middleware/cors.ts +96 -0
- package/src/middleware/form.ts +59 -0
- package/src/middleware/group.ts +68 -0
- package/src/middleware/index.ts +47 -0
- package/src/middleware/json.ts +55 -0
- package/src/middleware/logger.ts +18 -0
- package/src/middleware/parse.ts +93 -0
- package/src/middleware/session.ts +136 -0
- package/src/middleware/tag.ts +15 -0
- package/src/middleware/text.ts +45 -0
- package/src/proxy.ts +59 -0
- package/src/router.ts +301 -0
- package/src/static.ts +231 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import {Logger} from "./logger";
|
|
2
|
+
import {Session} from "./session";
|
|
3
|
+
import {IncomingHttpHeaders, IncomingMessage, OutgoingHttpHeaders, ServerResponse} from "http";
|
|
4
|
+
import {normalizePath, parseSearchParams} from "./tokenize-match";
|
|
5
|
+
import {URL} from "url";
|
|
6
|
+
import {newURL} from "./helpers";
|
|
7
|
+
import {CookieSerializeOptions, serialize} from "cookie";
|
|
8
|
+
|
|
9
|
+
export type Method =
|
|
10
|
+
"get"
|
|
11
|
+
| "post"
|
|
12
|
+
| "put"
|
|
13
|
+
| "delete"
|
|
14
|
+
| "patch"
|
|
15
|
+
| "options"
|
|
16
|
+
| "GET"
|
|
17
|
+
| "POST"
|
|
18
|
+
| "PUT"
|
|
19
|
+
| "DELETE"
|
|
20
|
+
| "PATCH"
|
|
21
|
+
| "OPTIONS";
|
|
22
|
+
|
|
23
|
+
export type Handler<T = boolean | void | any> = ((ctx: Context) => Promise<T>) | ((ctx: Context) => T);
|
|
24
|
+
|
|
25
|
+
export type ErrorHandler<T = boolean | void | any> =
|
|
26
|
+
((e: unknown, ctx: Context) => Promise<T>)
|
|
27
|
+
| ((e: unknown, ctx: Context) => T);
|
|
28
|
+
|
|
29
|
+
export class Context {
|
|
30
|
+
public readonly url: URL; // new URL(req.url ? req.url : "/", `http://${req.headers.host}`)
|
|
31
|
+
public readonly startMS: number; // Date.now()
|
|
32
|
+
public session?: Session; // a middleware will fill this
|
|
33
|
+
public results: any[]; // handlers will fill this
|
|
34
|
+
public readonly path: string; // normalized path
|
|
35
|
+
public readonly hash: string; // from this.url.hash
|
|
36
|
+
public readonly method: string; // from this.url.method
|
|
37
|
+
public headers: IncomingHttpHeaders; // from this.req.headers
|
|
38
|
+
public readonly cookies: { [name: string]: string }; // a middleware will fill this
|
|
39
|
+
public query: { [name: string]: string | string[] }; // parseSearchParams will fill this with this.url.searchParams
|
|
40
|
+
public params: { [name: string]: string | undefined } = {}; // the router will fill this
|
|
41
|
+
public buffer?: Buffer; // empty buffer. middleware must read it
|
|
42
|
+
public readonly remoteAddress?: string;
|
|
43
|
+
public body: any; // a middleware will fill this reading the buffer
|
|
44
|
+
constructor(public readonly uuid: string, public readonly req: IncomingMessage, public readonly res: ServerResponse, public readonly logger: Logger) {
|
|
45
|
+
this.body = undefined as any;
|
|
46
|
+
this.res.removeHeader("Date");
|
|
47
|
+
this.url = newURL(req.url ? req.url : "/", `http://${req.headers.host}`) as URL;
|
|
48
|
+
this.method = req.method ? req.method.toUpperCase() as string : "GET";
|
|
49
|
+
this.path = normalizePath(this.url.pathname); // normalized path
|
|
50
|
+
this.hash = this.url.hash;
|
|
51
|
+
this.query = parseSearchParams(this.url.searchParams);
|
|
52
|
+
//this.buffer = Buffer.from("");
|
|
53
|
+
this.remoteAddress = req.socket.remoteAddress;
|
|
54
|
+
this.cookies = {}; // a middleware will fill
|
|
55
|
+
this.headers = req.headers;
|
|
56
|
+
this.startMS = Date.now();
|
|
57
|
+
this.results = []; // handlers will fill this
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
public async close(): Promise<void> {
|
|
61
|
+
return this.end({
|
|
62
|
+
status: 400,
|
|
63
|
+
headers: {
|
|
64
|
+
connection: "close"
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
public addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse {
|
|
70
|
+
const c = this.res.getHeader("Vary");
|
|
71
|
+
const current = c ? c instanceof Array ? c.join(", ") : String(c) : "";
|
|
72
|
+
const nV = value instanceof Array ? value.join(", ") : String(value);
|
|
73
|
+
const newValue = current ? `${current}, ${nV}` : nV;
|
|
74
|
+
return this.res.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
public setHeader(name: string, value: number | string | ReadonlyArray<string>): ServerResponse {
|
|
78
|
+
return this.res.setHeader(name, value);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
public setCookie(name: string, value: string, options?: CookieSerializeOptions): ServerResponse {
|
|
82
|
+
return this.setHeader('Set-Cookie', serialize(name, String(value), options));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
public async end({status, headers, body}: {
|
|
86
|
+
body?: any;
|
|
87
|
+
status: number;
|
|
88
|
+
headers: OutgoingHttpHeaders;
|
|
89
|
+
}): Promise<void> {
|
|
90
|
+
return new Promise<void>((resolve, reject) => {
|
|
91
|
+
try {
|
|
92
|
+
if (this.res.headersSent) {
|
|
93
|
+
reject(new Error("already ended"));
|
|
94
|
+
} else {
|
|
95
|
+
this.res.statusCode = status;
|
|
96
|
+
const keys = Object.keys(headers);
|
|
97
|
+
for (const key of keys) {
|
|
98
|
+
if (headers[key] !== undefined) {
|
|
99
|
+
this.res.setHeader(key, headers[key] as any);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
this.res.end(body !== undefined ? (body instanceof Buffer ? body : String(body)) : undefined, () => {
|
|
103
|
+
resolve();
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
} catch (e) {
|
|
107
|
+
reject(e);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
113
|
+
public async json(body: any, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
|
|
114
|
+
return this.end({
|
|
115
|
+
status: status !== undefined ? status : 200,
|
|
116
|
+
headers: {
|
|
117
|
+
['Content-Type']: 'application/json; charset=utf-8',
|
|
118
|
+
...headers,
|
|
119
|
+
},
|
|
120
|
+
body: JSON.stringify(body)
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
public async text(text: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
|
|
125
|
+
return this.end({
|
|
126
|
+
status: status !== undefined ? status : 200,
|
|
127
|
+
headers: {
|
|
128
|
+
['Content-Type']: 'plain/text; charset=utf-8',
|
|
129
|
+
...headers
|
|
130
|
+
},
|
|
131
|
+
body: text
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
public async html(html: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
|
|
136
|
+
return this.end({
|
|
137
|
+
status: status !== undefined ? status : 200,
|
|
138
|
+
headers: {
|
|
139
|
+
['Content-Type']: 'text/html; charset=utf-8',
|
|
140
|
+
...headers
|
|
141
|
+
},
|
|
142
|
+
body: html
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
public async redirect(url: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
|
|
147
|
+
return this.end({
|
|
148
|
+
status: status !== undefined ? status : 302,
|
|
149
|
+
headers: {
|
|
150
|
+
['Location']: url,
|
|
151
|
+
...headers
|
|
152
|
+
}
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
@@ -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,51 @@
|
|
|
1
|
+
import {Logger} from "./logger";
|
|
2
|
+
import {LoggerFormatter} from "./formatter";
|
|
3
|
+
import {LoggerTransport} from "./transport";
|
|
4
|
+
import {LogLevel} from "./common";
|
|
5
|
+
import {ConfigStore} from "../config";
|
|
6
|
+
|
|
7
|
+
const loggerContainer: Map<string, Logger> = new Map<string, Logger>();
|
|
8
|
+
const DEFAULT_ENV_NAME = "LOG_LEVEL";
|
|
9
|
+
|
|
10
|
+
export const getLogger = (identifier: string, options?: { formatter?: LoggerFormatter, transports?: LoggerTransport[] }, useCache = true): Logger => {
|
|
11
|
+
if (typeof identifier !== "string" && typeof identifier !== "undefined") {
|
|
12
|
+
throw new Error("Bad log identifier");
|
|
13
|
+
}
|
|
14
|
+
if (useCache && loggerContainer.has(identifier)) {
|
|
15
|
+
return loggerContainer.get(identifier) as Logger;
|
|
16
|
+
} else {
|
|
17
|
+
const envVarName = `LOG_LEVEL_${identifier}`;
|
|
18
|
+
const level = ConfigStore.getConfig(envVarName) ? ConfigStore.getConfig(envVarName) as LogLevel : ConfigStore.getConfig(DEFAULT_ENV_NAME, "info") as LogLevel;
|
|
19
|
+
const factory = getLoggerFactory();
|
|
20
|
+
const logger = factory({identifier, level, options});
|
|
21
|
+
if (useCache) {
|
|
22
|
+
loggerContainer.set(identifier, logger);
|
|
23
|
+
}
|
|
24
|
+
return logger;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export type LoggerFactory = (args: { identifier: string, level: LogLevel; options?: { transports?: LoggerTransport[]; formatter?: LoggerFormatter; } }) => Logger;
|
|
29
|
+
|
|
30
|
+
const defaultLoggerFactory: LoggerFactory = ({identifier, options, level}): Logger => {
|
|
31
|
+
return new Logger(identifier, level, options);
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
let customLoggerFactory: LoggerFactory | undefined = undefined;
|
|
35
|
+
|
|
36
|
+
export const setLoggerFactory = (factory: LoggerFactory): LoggerFactory => {
|
|
37
|
+
if (customLoggerFactory !== undefined) {
|
|
38
|
+
throw new Error("cannot change logger factory. it has been used already.");
|
|
39
|
+
}
|
|
40
|
+
customLoggerFactory = factory;
|
|
41
|
+
return customLoggerFactory;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export const getLoggerFactory = (): LoggerFactory => {
|
|
45
|
+
if (customLoggerFactory) {
|
|
46
|
+
return customLoggerFactory;
|
|
47
|
+
} else {
|
|
48
|
+
customLoggerFactory = defaultLoggerFactory;
|
|
49
|
+
return defaultLoggerFactory;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import {LogLevel} from "./common";
|
|
2
|
+
|
|
3
|
+
export type LoggerFormatter = (args: { identifier: string, level: LogLevel, message: string }) => string;
|
|
4
|
+
|
|
5
|
+
export const defaultLoggerFormatter: LoggerFormatter =
|
|
6
|
+
({identifier, level, message}) => `${new Date().toISOString()} ${process.pid} ` +
|
|
7
|
+
`${identifier ? `[${identifier}] ` : ""}` +
|
|
8
|
+
`${level !== "info" ? (level === "error" || level === "warn" ? `[${level.toUpperCase()}] ` : `[${level}] `) : ""}` +
|
|
9
|
+
`${message}`;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import {format} from "util";
|
|
2
|
+
import {EventEmitter} from "events";
|
|
3
|
+
import {ConsoleTransport, FileTransport, LoggerTransport, LoggerTransportWriteArgs, WriteArgs} from "./transport";
|
|
4
|
+
import {defaultLoggerFormatter, LoggerFormatter} from "./formatter";
|
|
5
|
+
import {LoggerEvents, LogLevel} from "./common";
|
|
6
|
+
|
|
7
|
+
const defaultLoggerTransports: () => LoggerTransport[] = () => [
|
|
8
|
+
ConsoleTransport(),
|
|
9
|
+
FileTransport()
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
const LOG_LEVEL_MAP =
|
|
13
|
+
{
|
|
14
|
+
"error": 1,
|
|
15
|
+
"warn": 2,
|
|
16
|
+
"info": 3,
|
|
17
|
+
"debug": 4,
|
|
18
|
+
"trace": 5,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export interface Logger {
|
|
22
|
+
log(message?: any, ...optionalParams: any[]): void;
|
|
23
|
+
|
|
24
|
+
info(message?: any, ...optionalParams: any[]): void;
|
|
25
|
+
|
|
26
|
+
trace(message?: any, ...optionalParams: any[]): void;
|
|
27
|
+
|
|
28
|
+
debug(message?: any, ...optionalParams: any[]): void;
|
|
29
|
+
|
|
30
|
+
warn(message?: any, ...optionalParams: any[]): void;
|
|
31
|
+
|
|
32
|
+
error(message?: any, ...optionalParams: any[]): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class Logger extends EventEmitter implements Logger {
|
|
36
|
+
|
|
37
|
+
protected readonly options: { transports: LoggerTransport[]; formatter: LoggerFormatter; };
|
|
38
|
+
|
|
39
|
+
constructor(protected readonly identifier: string, protected readonly level: LogLevel = "info", options?: { transports?: LoggerTransport[]; formatter?: LoggerFormatter; }) {
|
|
40
|
+
super();
|
|
41
|
+
if (!LOG_LEVEL_MAP[level]) {
|
|
42
|
+
throw new Error(`Unknown level [${level}]`);
|
|
43
|
+
}
|
|
44
|
+
this.on(LoggerEvents.error, (e) => {
|
|
45
|
+
console.error(e);
|
|
46
|
+
});
|
|
47
|
+
this.options = {
|
|
48
|
+
transports: options && options.transports !== undefined ? options.transports : defaultLoggerTransports(),
|
|
49
|
+
formatter: options && options.formatter !== undefined ? options.formatter : defaultLoggerFormatter,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
protected write(args: WriteArgs): void {
|
|
54
|
+
try {
|
|
55
|
+
let eventArgs: LoggerTransportWriteArgs | undefined = undefined;
|
|
56
|
+
const tR = [];
|
|
57
|
+
for (const transport of this.options.transports) {
|
|
58
|
+
if (LOG_LEVEL_MAP[transport.level ? transport.level : this.level] >= LOG_LEVEL_MAP[args.level]) {
|
|
59
|
+
try {
|
|
60
|
+
eventArgs = eventArgs ? eventArgs : {
|
|
61
|
+
out: this.options.formatter({
|
|
62
|
+
identifier: this.identifier,
|
|
63
|
+
level: args.level,
|
|
64
|
+
message: format(args.message, ...args.optionalParams)
|
|
65
|
+
}),
|
|
66
|
+
...args
|
|
67
|
+
};
|
|
68
|
+
tR.push(transport.write(eventArgs));
|
|
69
|
+
} catch (e2) {
|
|
70
|
+
this.emit(LoggerEvents.error, e2);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
Promise.all(tR).catch((e) => {
|
|
75
|
+
this.emit(LoggerEvents.error, e);
|
|
76
|
+
});
|
|
77
|
+
} catch (e) {
|
|
78
|
+
this.emit(LoggerEvents.error, e);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
83
|
+
public debug(message?: any, ...optionalParams: any[]): void {
|
|
84
|
+
return this.write({level: "debug", message, optionalParams});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
88
|
+
public error(message?: any, ...optionalParams: any[]): void {
|
|
89
|
+
return this.write({level: "error", message, optionalParams});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
93
|
+
public info(message?: any, ...optionalParams: any[]): void {
|
|
94
|
+
return this.write({level: "info", message, optionalParams});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
98
|
+
public log(message?: any, ...optionalParams: any[]): void {
|
|
99
|
+
return this.write({level: "info", message, optionalParams});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
103
|
+
public trace(message?: any, ...optionalParams: any[]): void {
|
|
104
|
+
return this.write({level: "trace", message, optionalParams});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
108
|
+
public warn(message?: any, ...optionalParams: any[]): void {
|
|
109
|
+
return this.write({level: "warn", message, optionalParams});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import {createWriteStream} from "fs";
|
|
2
|
+
import {resolve} from "path";
|
|
3
|
+
import {LogLevel} from "./common";
|
|
4
|
+
|
|
5
|
+
export interface WriteArgs {
|
|
6
|
+
level: LogLevel;
|
|
7
|
+
message?: any;
|
|
8
|
+
optionalParams: any[]
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface LoggerTransportWriteArgs extends WriteArgs {
|
|
12
|
+
out: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface LoggerTransport {
|
|
16
|
+
level?: LogLevel;
|
|
17
|
+
|
|
18
|
+
write(args: LoggerTransportWriteArgs): Promise<void> | void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const ConsoleTransport: (color?: boolean, level?: LogLevel) => LoggerTransport = (color = true, level?: LogLevel) => {
|
|
22
|
+
return {
|
|
23
|
+
level,
|
|
24
|
+
write: async ({level, out}: LoggerTransportWriteArgs): Promise<void> => {
|
|
25
|
+
if (color) {
|
|
26
|
+
switch (level) {
|
|
27
|
+
case "warn":
|
|
28
|
+
console.warn("\x1b[33m%s\x1b[0m", out);
|
|
29
|
+
break;
|
|
30
|
+
case "error":
|
|
31
|
+
console.error("\x1b[31m%s\x1b[0m", out);
|
|
32
|
+
break;
|
|
33
|
+
case "trace":
|
|
34
|
+
console.log("\x1b[34m%s\x1b[0m", out);
|
|
35
|
+
break;
|
|
36
|
+
case "debug":
|
|
37
|
+
console.log("\x1b[36m%s\x1b[0m", out);
|
|
38
|
+
break;
|
|
39
|
+
default:
|
|
40
|
+
console[level](out);
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
} else {
|
|
44
|
+
console[level](out);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const FILE_TRANSPORT_ENVVAR = "LOG_FILE";
|
|
51
|
+
|
|
52
|
+
export const FileTransport: (filePath?: string | null, level?: LogLevel) => LoggerTransport = (filePath = process.env[FILE_TRANSPORT_ENVVAR] ? process.env[FILE_TRANSPORT_ENVVAR] : null, level?: LogLevel) => {
|
|
53
|
+
const fileHandler = filePath ? createWriteStream(resolve(filePath), {flags: "a"}) : null;
|
|
54
|
+
return {
|
|
55
|
+
level,
|
|
56
|
+
write: async ({out}: LoggerTransportWriteArgs): Promise<void> => {
|
|
57
|
+
if (fileHandler) {
|
|
58
|
+
return new Promise((resolve, reject) => {
|
|
59
|
+
fileHandler.write(`${out}\n`, (err) => {
|
|
60
|
+
if (err) {
|
|
61
|
+
reject(err);
|
|
62
|
+
} else {
|
|
63
|
+
resolve();
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {defaultLoggerFormatter, getLogger, Logger} from "./logger";
|
|
2
|
+
import {IncomingMessage} from "http";
|
|
3
|
+
import {URL} from "url";
|
|
4
|
+
import {newURL} from "./helpers";
|
|
5
|
+
import {normalizePath} from "./tokenize-match";
|
|
6
|
+
|
|
7
|
+
export const defaultLoggerFactory = (uuid: string, req: IncomingMessage): Logger => {
|
|
8
|
+
const url = newURL(req.url ? req.url : "/", `http://${req.headers.host}`) as URL;
|
|
9
|
+
const method = req.method ? req.method.toUpperCase() as string : "GET";
|
|
10
|
+
const path = normalizePath(url.pathname); // normalized path
|
|
11
|
+
const pathToEnv = path.replace(/\//ig, "_").toUpperCase();
|
|
12
|
+
const identifier = `${pathToEnv === "_" ? "" : pathToEnv.substring(1)}${method.toUpperCase()}`;
|
|
13
|
+
const remoteAddress = req.socket.remoteAddress;
|
|
14
|
+
return getLogger(identifier, {
|
|
15
|
+
formatter: (args) => {
|
|
16
|
+
args.message = `${method} ${url}${uuid ? ` [${uuid}]` : ""}${remoteAddress ? ` (${remoteAddress})` : ""} ${args.message}`;
|
|
17
|
+
return defaultLoggerFormatter(args);
|
|
18
|
+
}
|
|
19
|
+
}, false);
|
|
20
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import {Context, Handler} from "./context";
|
|
2
|
+
import {parse, ParseOptions, ParserInterface} from "@miqro/parser";
|
|
3
|
+
import {GroupPolicy, SessionHandlerOptions} from "./session";
|
|
4
|
+
|
|
5
|
+
export const ResultParser = (options: ParseOptions | ParseOptions[] | string, parser?: ParserInterface): Handler => {
|
|
6
|
+
return async function ResultParser(ctx: Context): Promise<any> {
|
|
7
|
+
if (!ctx.results || ctx.results.length === 0) {
|
|
8
|
+
ctx.logger.debug(`not parsing results`);
|
|
9
|
+
return undefined;
|
|
10
|
+
} else {
|
|
11
|
+
const index = ctx.results.length - 1;
|
|
12
|
+
const lastResult = ctx.results[index];
|
|
13
|
+
ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
|
|
14
|
+
try {
|
|
15
|
+
if (options instanceof Array) {
|
|
16
|
+
for (let i = 0; i < options.length; i++) {
|
|
17
|
+
const o = options[i];
|
|
18
|
+
try {
|
|
19
|
+
const mappedResults = (parser ? parser : {parse}).parse(lastResult, o.options, o.mode, `ctx.results[${index}]`);
|
|
20
|
+
ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
|
|
21
|
+
return mappedResults;
|
|
22
|
+
} catch (e) {
|
|
23
|
+
if (i === options.length - 1) {
|
|
24
|
+
throw e;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
} else if (typeof options !== "string") {
|
|
29
|
+
const mappedResults = (parser ? parser : {parse}).parse(lastResult, options.options, options.mode, `ctx.results[${index}]`);
|
|
30
|
+
ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
|
|
31
|
+
return mappedResults;
|
|
32
|
+
} else {
|
|
33
|
+
const mappedResults = (parser ? parser : {parse}).parse(lastResult, options, "no_extra", `ctx.results[${index}]`);
|
|
34
|
+
ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
|
|
35
|
+
return mappedResults;
|
|
36
|
+
}
|
|
37
|
+
} catch (e) {
|
|
38
|
+
ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
|
|
39
|
+
throw e;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const ResponseHandler = (): Handler<void> => async (ctx: Context): Promise<void> => {
|
|
46
|
+
ctx.logger.trace("results [%o]", ctx.results);
|
|
47
|
+
if (!ctx.results || ctx.results.length === 0) {
|
|
48
|
+
throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
|
|
49
|
+
} else {
|
|
50
|
+
const lastResult = ctx.results[ctx.results.length - 1];
|
|
51
|
+
ctx.logger.debug("response [%o]", lastResult);
|
|
52
|
+
if (lastResult !== undefined) {
|
|
53
|
+
await ctx.json(lastResult);
|
|
54
|
+
} else {
|
|
55
|
+
throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export interface HandlerWithOptions extends RouterHandlerOptions {
|
|
61
|
+
handler: Handler | Array<Handler>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface RouteOptions {
|
|
65
|
+
name?: string;
|
|
66
|
+
description?: string;
|
|
67
|
+
policy?: GroupPolicy;
|
|
68
|
+
request?: {
|
|
69
|
+
headers?: ParseOptions | ParseOptions[];
|
|
70
|
+
query?: ParseOptions | boolean | ParseOptions[] | string;
|
|
71
|
+
params?: ParseOptions | boolean | ParseOptions[] | string;
|
|
72
|
+
body?: ParseOptions | boolean | ParseOptions[] | string;
|
|
73
|
+
};
|
|
74
|
+
response?: {
|
|
75
|
+
body?: boolean | ParseOptions | ParseOptions[] | string;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface RouteJSONDoc extends RouteOptions {
|
|
80
|
+
identifier: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface RouterJSONDoc {
|
|
84
|
+
[path: string]: {
|
|
85
|
+
[method: string]: RouteJSONDoc
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface RouterHandlerOptions extends RouteOptions {
|
|
90
|
+
parser?: ParserInterface;
|
|
91
|
+
middleware?: Handler | Handler[];
|
|
92
|
+
session?: SessionHandlerOptions | Handler;
|
|
93
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import {Dict} from "@miqro/parser";
|
|
2
|
+
import {Context} from "../context";
|
|
3
|
+
|
|
4
|
+
export interface SessionHandlerOptions {
|
|
5
|
+
authService: {
|
|
6
|
+
verify(args: { token: string; ctx: Context }): Promise<Session | null>;
|
|
7
|
+
};
|
|
8
|
+
options?: {
|
|
9
|
+
tokenLocation: "header" | "query" | "cookie";
|
|
10
|
+
tokenLocationName: string | ((ctx: Context) => Promise<string>);
|
|
11
|
+
setCookieOptions?: {
|
|
12
|
+
httpOnly: boolean;
|
|
13
|
+
secure: boolean;
|
|
14
|
+
path: string | ((ctx: Context) => Promise<string>);
|
|
15
|
+
sameSite: "lax" | "strict" | "none";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface NoTokenSession extends Dict<any> {
|
|
21
|
+
account: string;
|
|
22
|
+
username: string;
|
|
23
|
+
groups: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface Session extends NoTokenSession {
|
|
27
|
+
token: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type GroupPolicyType = "at_least_one" | "all";
|
|
31
|
+
|
|
32
|
+
export type GroupPolicyGroups = string | string[];
|
|
33
|
+
|
|
34
|
+
export interface GroupPolicy {
|
|
35
|
+
groups: GroupPolicyGroups[];
|
|
36
|
+
groupPolicy: GroupPolicyType;
|
|
37
|
+
}
|