@miqro/core 1.5.8 → 1.5.11

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.
Files changed (50) hide show
  1. package/dist/static.d.ts +1 -0
  2. package/dist/static.js +15 -0
  3. package/dist/static.js.map +1 -1
  4. package/package.json +4 -4
  5. package/src/api-router.ts +51 -0
  6. package/src/app.ts +136 -0
  7. package/src/common/api-router-helpers.ts +32 -0
  8. package/src/common/api-router-utils.ts +206 -0
  9. package/src/common/config/config.ts +99 -0
  10. package/src/common/config/featuretoggle.ts +6 -0
  11. package/src/common/config/index.ts +3 -0
  12. package/src/common/config/loader.ts +80 -0
  13. package/src/common/context.ts +156 -0
  14. package/src/common/error/badrequesterror.ts +6 -0
  15. package/src/common/error/configfilenotfound.ts +6 -0
  16. package/src/common/error/forbiddenerror.ts +6 -0
  17. package/src/common/error/index.ts +6 -0
  18. package/src/common/error/notfound.ts +6 -0
  19. package/src/common/error/notimplemented.ts +6 -0
  20. package/src/common/error/unauthorizederror.ts +6 -0
  21. package/src/common/helpers.ts +11 -0
  22. package/src/common/index.ts +7 -0
  23. package/src/common/logger/common.ts +6 -0
  24. package/src/common/logger/factory.ts +51 -0
  25. package/src/common/logger/formatter.ts +9 -0
  26. package/src/common/logger/index.ts +6 -0
  27. package/src/common/logger/logger.ts +114 -0
  28. package/src/common/logger/transport.ts +71 -0
  29. package/src/common/router-helpers.ts +20 -0
  30. package/src/common/router-utils.ts +93 -0
  31. package/src/common/session/common.ts +37 -0
  32. package/src/common/session/index.ts +2 -0
  33. package/src/common/session/service.ts +157 -0
  34. package/src/common/tokenize-match.ts +152 -0
  35. package/src/index.ts +7 -0
  36. package/src/middleware/buffer.ts +80 -0
  37. package/src/middleware/cookie.ts +20 -0
  38. package/src/middleware/cors.ts +96 -0
  39. package/src/middleware/form.ts +59 -0
  40. package/src/middleware/group.ts +68 -0
  41. package/src/middleware/index.ts +47 -0
  42. package/src/middleware/json.ts +55 -0
  43. package/src/middleware/logger.ts +18 -0
  44. package/src/middleware/parse.ts +93 -0
  45. package/src/middleware/session.ts +136 -0
  46. package/src/middleware/tag.ts +15 -0
  47. package/src/middleware/text.ts +45 -0
  48. package/src/proxy.ts +59 -0
  49. package/src/router.ts +301 -0
  50. package/src/static.ts +231 -0
@@ -0,0 +1,80 @@
1
+ import {extname, resolve} from "path";
2
+ import {existsSync, readdirSync, readFileSync} from "fs";
3
+ import {ConfigOutput, ConfigPathResolver, ConfigStore, LoadConfigOut} from "./config";
4
+
5
+ interface Logger {
6
+ log(message?: any, ...optionalParams: any[]): void;
7
+
8
+ info(message?: any, ...optionalParams: any[]): void;
9
+
10
+ trace(message?: any, ...optionalParams: any[]): void;
11
+
12
+ debug(message?: any, ...optionalParams: any[]): void;
13
+
14
+ warn(message?: any, ...optionalParams: any[]): void;
15
+
16
+ error(message?: any, ...optionalParams: any[]): void;
17
+ }
18
+
19
+
20
+ class ConfigFileNotFoundError extends Error {
21
+ constructor(args: any) {
22
+ super(args);
23
+ this.name = "ConfigFileNotFoundError";
24
+ }
25
+ }
26
+
27
+ export const loadConfigString = (envFileContent: string, combined?: ConfigOutput): ConfigOutput => {
28
+ const ret: ConfigOutput = {};
29
+ envFileContent.split("\n")
30
+ .filter(value => value && value.length > 0 && value.substring(0, 1) !== "#")
31
+ .forEach((line) => {
32
+ const separator = line.indexOf("=");
33
+ if (separator === -1) {
34
+ throw new Error(`cannot read ${line}`);
35
+ }
36
+ ret[line.substring(0, separator)] = line.substring(separator + 1);
37
+ });
38
+ const keys = Object.keys(ret);
39
+ for (const key of keys) {
40
+ if (combined) {
41
+ combined[key] = ret[key];
42
+ }
43
+ ConfigStore.putConfig(key, ret[key]);
44
+ }
45
+ return ret;
46
+ }
47
+
48
+ export const loadConfigFile = (envFilePath: string, combined?: ConfigOutput, logger?: Logger): ConfigOutput => {
49
+ if (!existsSync(envFilePath)) {
50
+ throw new ConfigFileNotFoundError(`config file [${envFilePath}] doesnt exists!`);
51
+ } else {
52
+ if (logger) {
53
+ logger.trace(`loading config from [${envFilePath}].`);
54
+ }
55
+ return loadConfigString(readFileSync(envFilePath).toString(), combined);
56
+ }
57
+ };
58
+
59
+ const MISSED_TO_RUNMIQRO_INIT = (configDirname: string): string => `no config loaded. env files in [${configDirname}] doesnt exist!.`;
60
+
61
+ export const loadConfig = (configDirname: string = ConfigPathResolver.getConfigDirname(), logger?: Logger): LoadConfigOut => {
62
+ const outputs: ConfigOutput[] = [];
63
+ const combined = {};
64
+ if (existsSync(configDirname)) {
65
+ const configFiles = readdirSync(configDirname);
66
+ for (const configFile of configFiles) {
67
+ const configFilePath = resolve(configDirname, configFile);
68
+ const ext = extname(configFilePath);
69
+ if (ext === ".env") {
70
+ outputs.push(loadConfigFile(configFilePath, combined, logger));
71
+ }
72
+ }
73
+ if (logger && configFiles.length === 0) {
74
+ logger.debug(MISSED_TO_RUNMIQRO_INIT(configDirname));
75
+ }
76
+ } else if (logger) {
77
+ logger.debug(MISSED_TO_RUNMIQRO_INIT(configDirname));
78
+ }
79
+ return {combined, outputs};
80
+ };
@@ -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,6 @@
1
+ export class BadRequestError extends Error {
2
+ constructor(message = "BAD REQUEST") {
3
+ super(message);
4
+ this.name = "BadRequestError";
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ export class ConfigFileNotFoundError extends Error {
2
+ constructor(message = "NOT FOUND") {
3
+ super(message);
4
+ this.name = "ConfigFileNotFoundError";
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ export class ForbiddenError extends Error {
2
+ constructor(message = "FORBIDDEN") {
3
+ super(message);
4
+ this.name = "ForbiddenError";
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./badrequesterror";
2
+ export * from "./unauthorizederror";
3
+ export * from "./forbiddenerror";
4
+ export * from "./notfound";
5
+ export * from "./notimplemented";
6
+ export * from "./configfilenotfound";
@@ -0,0 +1,6 @@
1
+ export class NotFoundError extends Error {
2
+ constructor(message = "NOT FOUND") {
3
+ super(message);
4
+ this.name = "NotFoundError";
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ export class MethodNotImplementedError extends Error {
2
+ constructor(message = "NOT IMPLEMENTED") {
3
+ super(message);
4
+ this.name = "MethodNotImplementedError";
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ export class UnAuthorizedError extends Error {
2
+ constructor(message = "UNAUTHORIZED") {
3
+ super(message);
4
+ this.name = "UnAuthorizedError";
5
+ }
6
+ }
@@ -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,7 @@
1
+ export * from "./context";
2
+ export * from "./router-helpers";
3
+ export * from "./api-router-helpers";
4
+ export * from "./session";
5
+ export * from "./error";
6
+ export * from "./config";
7
+ export * from "./logger";
@@ -0,0 +1,6 @@
1
+ export type LogLevel = "error" | "warn" | "info" | "debug" | "trace";
2
+
3
+
4
+ export const LoggerEvents = {
5
+ error: "error"
6
+ };
@@ -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,6 @@
1
+ export {LogLevel} from "./common";
2
+ export * from "./factory";
3
+ export * from "./formatter";
4
+ export * from "./logger";
5
+ export * from "./transport";
6
+
@@ -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
+ }