@meghjs/core 0.5.4 → 0.6.0
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 +54 -137
- package/dist/common/container.js +0 -1
- package/dist/common/container.js.map +1 -1
- package/dist/common/exceptions/http-exceptions.d.ts +1 -50
- package/dist/common/exceptions/http-exceptions.js +15 -80
- package/dist/common/exceptions/http-exceptions.js.map +1 -1
- package/dist/common/exceptions/system-exception.d.ts +0 -10
- package/dist/common/exceptions/system-exception.js +7 -12
- package/dist/common/exceptions/system-exception.js.map +1 -1
- package/dist/common/utils/compiled-validation.d.ts +43 -0
- package/dist/common/utils/compiled-validation.js +299 -0
- package/dist/common/utils/compiled-validation.js.map +1 -0
- package/dist/common/utils/object-utils.d.ts +4 -0
- package/dist/common/utils/object-utils.js +44 -7
- package/dist/common/utils/object-utils.js.map +1 -1
- package/dist/common/utils/path-utils.d.ts +7 -0
- package/dist/common/utils/path-utils.js +15 -0
- package/dist/common/utils/path-utils.js.map +1 -1
- package/dist/config/environment-variables.d.ts +2 -0
- package/dist/config/environment-variables.js +24 -12
- package/dist/config/environment-variables.js.map +1 -1
- package/dist/core/application.d.ts +90 -12
- package/dist/core/application.js +166 -100
- package/dist/core/application.js.map +1 -1
- package/dist/core/interfaces.d.ts +48 -4
- package/dist/core/router.d.ts +59 -9
- package/dist/core/router.js +233 -123
- package/dist/core/router.js.map +1 -1
- package/dist/core/testing.js +2 -12
- package/dist/core/testing.js.map +1 -1
- package/dist/core/types.d.ts +6 -0
- package/dist/errors/error-handler.d.ts +56 -0
- package/dist/errors/error-handler.js +206 -0
- package/dist/errors/error-handler.js.map +1 -0
- package/dist/errors/exception-filter.d.ts +96 -0
- package/dist/errors/exception-filter.js +68 -0
- package/dist/errors/exception-filter.js.map +1 -0
- package/dist/errors/http-exceptions.d.ts +413 -0
- package/dist/errors/http-exceptions.js +155 -0
- package/dist/errors/http-exceptions.js.map +1 -0
- package/dist/errors/index.d.ts +4 -0
- package/dist/errors/index.js +24 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/events/event-subscriber.js +14 -3
- package/dist/events/event-subscriber.js.map +1 -1
- package/dist/events/socket-dispatcher.d.ts +1 -3
- package/dist/events/socket-dispatcher.js +2 -10
- package/dist/events/socket-dispatcher.js.map +1 -1
- package/dist/http/multipart.js.map +1 -1
- package/dist/http/params.js +3 -1
- package/dist/http/params.js.map +1 -1
- package/dist/http/route-methods.js.map +1 -1
- package/dist/http/validator-extend.js +1 -1
- package/dist/http/validator-extend.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/dist/observability/health.d.ts +45 -0
- package/dist/observability/health.js +74 -0
- package/dist/observability/health.js.map +1 -0
- package/dist/observability/index.d.ts +3 -0
- package/dist/observability/index.js +5 -0
- package/dist/observability/index.js.map +1 -1
- package/dist/observability/logger.js +8 -1
- package/dist/observability/logger.js.map +1 -1
- package/dist/observability/request-context.d.ts +29 -0
- package/dist/observability/request-context.js +54 -0
- package/dist/observability/request-context.js.map +1 -0
- package/dist/openapi/swagger-schema.d.ts +0 -2
- package/dist/openapi/swagger-schema.js +21 -5
- package/dist/openapi/swagger-schema.js.map +1 -1
- package/dist/orm/connect.d.ts +2 -0
- package/dist/orm/connect.js +6 -1
- package/dist/orm/connect.js.map +1 -1
- package/dist/orm/plugin.js +2 -0
- package/dist/orm/plugin.js.map +1 -1
- package/dist/plugins/plugin.d.ts +3 -0
- package/dist/plugins/plugin.js.map +1 -1
- package/dist/plugins/registry.js +1 -0
- package/dist/plugins/registry.js.map +1 -1
- package/dist/realtime/websocket.d.ts +1 -7
- package/dist/realtime/websocket.js +2 -18
- package/dist/realtime/websocket.js.map +1 -1
- package/dist/storage/file-storage.js +6 -4
- package/dist/storage/file-storage.js.map +1 -1
- package/dist/validator/compat.d.ts +5 -0
- package/dist/validator/compat.js +42 -0
- package/dist/validator/compat.js.map +1 -0
- package/dist/validator/compiler.d.ts +20 -0
- package/dist/validator/compiler.js +219 -0
- package/dist/validator/compiler.js.map +1 -0
- package/dist/validator/decorators.d.ts +81 -0
- package/dist/validator/decorators.js +377 -0
- package/dist/validator/decorators.js.map +1 -0
- package/dist/validator/index.d.ts +16 -0
- package/dist/validator/index.js +36 -0
- package/dist/validator/index.js.map +1 -0
- package/dist/validator/is-email.d.ts +25 -0
- package/dist/validator/is-email.js +204 -0
- package/dist/validator/is-email.js.map +1 -0
- package/dist/validator/messages.d.ts +20 -0
- package/dist/validator/messages.js +186 -0
- package/dist/validator/messages.js.map +1 -0
- package/dist/validator/metadata.d.ts +118 -0
- package/dist/validator/metadata.js +153 -0
- package/dist/validator/metadata.js.map +1 -0
- package/dist/validator/transform.d.ts +29 -0
- package/dist/validator/transform.js +210 -0
- package/dist/validator/transform.js.map +1 -0
- package/package.json +8 -3
|
@@ -5,11 +5,13 @@
|
|
|
5
5
|
* @url https://github.com/xtareq
|
|
6
6
|
*/
|
|
7
7
|
import { FastifyInstance } from "fastify";
|
|
8
|
-
import { IMeghApplication, MeghApplicationOptions, CorsOptions, GlobalOptions, CacheOptions, LifecycleHook } from "./interfaces";
|
|
8
|
+
import { IMeghApplication, MeghApplicationOptions, CorsOptions, GlobalOptions, CacheOptions, LifecycleHook, RunOptions } from "./interfaces";
|
|
9
|
+
import { ErrorLogger, ExceptionFilterLike, ErrorHandlerFunction } from "../errors";
|
|
9
10
|
import { Constructor } from "../common/helpers";
|
|
10
11
|
import { OpenApiUiOptions } from "../openapi/openapi";
|
|
11
12
|
import { MeghMiddleware } from "../http/middleware";
|
|
12
13
|
import { AutoControllerOptions } from "./types";
|
|
14
|
+
import { HealthCheck, HealthOptions } from "../observability/health";
|
|
13
15
|
import { MeghConfig } from "../config/config";
|
|
14
16
|
import { MeghAuthentication } from "../security/authentication";
|
|
15
17
|
export declare class MeghApplication implements IMeghApplication {
|
|
@@ -19,12 +21,10 @@ export declare class MeghApplication implements IMeghApplication {
|
|
|
19
21
|
private alreadyRun;
|
|
20
22
|
private hasSwagger;
|
|
21
23
|
private globalSwaggerOptions;
|
|
22
|
-
private isMapFeatures;
|
|
23
24
|
private registerControllerAuto;
|
|
24
25
|
private registerControllerPath;
|
|
25
26
|
private controllers;
|
|
26
27
|
private _hasWebsocket;
|
|
27
|
-
private io;
|
|
28
28
|
private scheduler;
|
|
29
29
|
private schedulerTasks;
|
|
30
30
|
private registerSchedulerAuto;
|
|
@@ -32,7 +32,11 @@ export declare class MeghApplication implements IMeghApplication {
|
|
|
32
32
|
private _workers;
|
|
33
33
|
private lifecycleHooks;
|
|
34
34
|
private closing;
|
|
35
|
+
private signalHandler;
|
|
35
36
|
private pluginNames;
|
|
37
|
+
private usesCache;
|
|
38
|
+
private health;
|
|
39
|
+
private errorHandler;
|
|
36
40
|
private constructor();
|
|
37
41
|
/** Names of the registered plugins, in registration order. */
|
|
38
42
|
getPlugins(): readonly string[];
|
|
@@ -72,7 +76,50 @@ export declare class MeghApplication implements IMeghApplication {
|
|
|
72
76
|
* @Authorized({ name: "oauth" }) // uses the "oauth" handler
|
|
73
77
|
*/
|
|
74
78
|
useAuthorization(authorization: Constructor<any> | Record<string, Constructor<any>>): this;
|
|
75
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Register global exception filters. They run in order, after any
|
|
81
|
+
* `@UseFilters` on the route or controller, and before Megh's default
|
|
82
|
+
* error response.
|
|
83
|
+
*
|
|
84
|
+
* app.useExceptionFilters([EntityNotFoundFilter, ProblemJsonFilter])
|
|
85
|
+
*
|
|
86
|
+
* Each entry can be a filter class (resolved through DI), a filter
|
|
87
|
+
* instance or a function `(error, ctx) => ...`.
|
|
88
|
+
*
|
|
89
|
+
* @see ExceptionFilter
|
|
90
|
+
*/
|
|
91
|
+
useExceptionFilters(filters: ExceptionFilterLike | ExceptionFilterLike[]): this;
|
|
92
|
+
/**
|
|
93
|
+
* Register a function that handles request errors. It is a global filter
|
|
94
|
+
* that sees every error: return a body to send it, return an `Error` to
|
|
95
|
+
* hand it on, or return nothing to fall back to the default response.
|
|
96
|
+
*
|
|
97
|
+
* app.useErrorHandler((error, { response }) => ({
|
|
98
|
+
* ok: false,
|
|
99
|
+
* message: response.body.message,
|
|
100
|
+
* }))
|
|
101
|
+
*/
|
|
102
|
+
useErrorHandler(handler: ErrorHandlerFunction): this;
|
|
103
|
+
/**
|
|
104
|
+
* Replace how errors answered with the default response are logged, or
|
|
105
|
+
* pass `false` to stop logging them.
|
|
106
|
+
*/
|
|
107
|
+
useErrorLogger(logger: ErrorLogger | false): this;
|
|
108
|
+
/** Install the error and not-found handlers on the Fastify instance. @internal */
|
|
109
|
+
installErrorHandling(): void;
|
|
110
|
+
/**
|
|
111
|
+
* Serve health routes: `GET /health` (liveness, always 200) and
|
|
112
|
+
* `GET /ready` (readiness: runs every health check, 503 if one fails).
|
|
113
|
+
* Plugins register their own checks, such as Megh ORM's `database`.
|
|
114
|
+
*
|
|
115
|
+
* app.useHealth({ checks: { redis: () => redis.ping() } })
|
|
116
|
+
*/
|
|
117
|
+
useHealth(options?: HealthOptions): this;
|
|
118
|
+
/**
|
|
119
|
+
* Add a readiness check, reported by `GET /ready` once `useHealth()` is on.
|
|
120
|
+
* It passes unless it throws, rejects or returns `false`.
|
|
121
|
+
*/
|
|
122
|
+
addHealthCheck(name: string, check: HealthCheck): this;
|
|
76
123
|
/**
|
|
77
124
|
* Register scheduled task classes.
|
|
78
125
|
*
|
|
@@ -87,7 +134,6 @@ export declare class MeghApplication implements IMeghApplication {
|
|
|
87
134
|
}): this;
|
|
88
135
|
useControllers(controllers: Constructor[] | AutoControllerOptions): this;
|
|
89
136
|
useStaticFiles(options?: any): this;
|
|
90
|
-
useHttps(options?: any): this;
|
|
91
137
|
useGlobal(options: GlobalOptions): this;
|
|
92
138
|
useSocketIo(options?: any): this;
|
|
93
139
|
/**
|
|
@@ -104,7 +150,6 @@ export declare class MeghApplication implements IMeghApplication {
|
|
|
104
150
|
useWorker(workers: Constructor<any>[]): this;
|
|
105
151
|
/** Close every registered worker, releasing their Redis connections. */
|
|
106
152
|
private _closeWorkers;
|
|
107
|
-
mapFeatures(): this;
|
|
108
153
|
/**
|
|
109
154
|
* True only when `NODE_ENV` is exactly `"development"`. An unset
|
|
110
155
|
* `NODE_ENV` counts as production, so dev-only features (API docs,
|
|
@@ -114,22 +159,45 @@ export declare class MeghApplication implements IMeghApplication {
|
|
|
114
159
|
private _mapControllers;
|
|
115
160
|
private _resolveControllerDir;
|
|
116
161
|
private autoControllers;
|
|
117
|
-
private _mapFeatures;
|
|
118
162
|
private handleSocket;
|
|
119
163
|
mapGet<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
|
|
120
|
-
useMiddleware:
|
|
164
|
+
useMiddleware: (middlewares: MeghMiddleware | Constructor<MeghMiddleware> | (MeghMiddleware | Constructor<MeghMiddleware>)[]) => /*elided*/ any;
|
|
165
|
+
authorized: (options?: string | {
|
|
166
|
+
[key: string]: unknown;
|
|
167
|
+
name?: string;
|
|
168
|
+
} | undefined) => /*elided*/ any;
|
|
121
169
|
useOpenApi: (options: import("../openapi/openapi").OpenApiOptions) => /*elided*/ any;
|
|
122
170
|
};
|
|
123
171
|
mapPost<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
|
|
124
|
-
useMiddleware:
|
|
172
|
+
useMiddleware: (middlewares: MeghMiddleware | Constructor<MeghMiddleware> | (MeghMiddleware | Constructor<MeghMiddleware>)[]) => /*elided*/ any;
|
|
173
|
+
authorized: (options?: string | {
|
|
174
|
+
[key: string]: unknown;
|
|
175
|
+
name?: string;
|
|
176
|
+
} | undefined) => /*elided*/ any;
|
|
125
177
|
useOpenApi: (options: import("../openapi/openapi").OpenApiOptions) => /*elided*/ any;
|
|
126
178
|
};
|
|
127
179
|
mapPut<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
|
|
128
|
-
useMiddleware:
|
|
180
|
+
useMiddleware: (middlewares: MeghMiddleware | Constructor<MeghMiddleware> | (MeghMiddleware | Constructor<MeghMiddleware>)[]) => /*elided*/ any;
|
|
181
|
+
authorized: (options?: string | {
|
|
182
|
+
[key: string]: unknown;
|
|
183
|
+
name?: string;
|
|
184
|
+
} | undefined) => /*elided*/ any;
|
|
185
|
+
useOpenApi: (options: import("../openapi/openapi").OpenApiOptions) => /*elided*/ any;
|
|
186
|
+
};
|
|
187
|
+
mapPatch<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
|
|
188
|
+
useMiddleware: (middlewares: MeghMiddleware | Constructor<MeghMiddleware> | (MeghMiddleware | Constructor<MeghMiddleware>)[]) => /*elided*/ any;
|
|
189
|
+
authorized: (options?: string | {
|
|
190
|
+
[key: string]: unknown;
|
|
191
|
+
name?: string;
|
|
192
|
+
} | undefined) => /*elided*/ any;
|
|
129
193
|
useOpenApi: (options: import("../openapi/openapi").OpenApiOptions) => /*elided*/ any;
|
|
130
194
|
};
|
|
131
195
|
mapDelete<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
|
|
132
|
-
useMiddleware:
|
|
196
|
+
useMiddleware: (middlewares: MeghMiddleware | Constructor<MeghMiddleware> | (MeghMiddleware | Constructor<MeghMiddleware>)[]) => /*elided*/ any;
|
|
197
|
+
authorized: (options?: string | {
|
|
198
|
+
[key: string]: unknown;
|
|
199
|
+
name?: string;
|
|
200
|
+
} | undefined) => /*elided*/ any;
|
|
133
201
|
useOpenApi: (options: import("../openapi/openapi").OpenApiOptions) => /*elided*/ any;
|
|
134
202
|
};
|
|
135
203
|
/**
|
|
@@ -155,5 +223,15 @@ export declare class MeghApplication implements IMeghApplication {
|
|
|
155
223
|
private assertNotStarted;
|
|
156
224
|
private runHooks;
|
|
157
225
|
private _autoSchedulerTasks;
|
|
158
|
-
|
|
226
|
+
/**
|
|
227
|
+
* Start the server.
|
|
228
|
+
*
|
|
229
|
+
* await app.run(3000)
|
|
230
|
+
* await app.run(3000, { host: "127.0.0.1" })
|
|
231
|
+
*
|
|
232
|
+
* The port defaults to the `PORT` environment variable, else `4000`. The
|
|
233
|
+
* host defaults to the `HOST` environment variable, else `0.0.0.0` so the
|
|
234
|
+
* app is reachable inside containers.
|
|
235
|
+
*/
|
|
236
|
+
run(port?: number, options?: RunOptions | CallableFunction): Promise<void>;
|
|
159
237
|
}
|
package/dist/core/application.js
CHANGED
|
@@ -48,7 +48,7 @@ const path_1 = __importDefault(require("path"));
|
|
|
48
48
|
const fs_1 = __importDefault(require("fs"));
|
|
49
49
|
const router_1 = require("./router");
|
|
50
50
|
const di_1 = require("../di");
|
|
51
|
-
const
|
|
51
|
+
const errors_1 = require("../errors");
|
|
52
52
|
const system_exception_1 = require("../common/exceptions/system-exception");
|
|
53
53
|
const swagger_schema_1 = require("../openapi/swagger-schema");
|
|
54
54
|
const responses_1 = require("../openapi/responses");
|
|
@@ -56,10 +56,14 @@ const request_body_1 = require("../openapi/request-body");
|
|
|
56
56
|
const query_params_1 = require("../openapi/query-params");
|
|
57
57
|
const branding_1 = require("../openapi/branding");
|
|
58
58
|
const scheduler_1 = require("../scheduler");
|
|
59
|
+
const schedule_registry_1 = require("../scheduler/schedule-registry");
|
|
59
60
|
const container_1 = require("../common/container");
|
|
60
61
|
const cache_1 = require("../observability/cache");
|
|
62
|
+
const health_1 = require("../observability/health");
|
|
61
63
|
const registry_1 = require("../plugins/registry");
|
|
62
64
|
const internal_logger_1 = require("../observability/internal-logger");
|
|
65
|
+
const path_utils_1 = require("../common/utils/path-utils");
|
|
66
|
+
const request_context_1 = require("../observability/request-context");
|
|
63
67
|
// ---------------------------------------------------------------------------
|
|
64
68
|
// Lazy loaders for optional peer dependencies
|
|
65
69
|
// ---------------------------------------------------------------------------
|
|
@@ -136,12 +140,10 @@ class MeghApplication {
|
|
|
136
140
|
alreadyRun = false;
|
|
137
141
|
hasSwagger = false;
|
|
138
142
|
globalSwaggerOptions;
|
|
139
|
-
isMapFeatures = false;
|
|
140
143
|
registerControllerAuto = false;
|
|
141
144
|
registerControllerPath = "src/controllers";
|
|
142
145
|
controllers = [];
|
|
143
146
|
_hasWebsocket = false;
|
|
144
|
-
io;
|
|
145
147
|
scheduler = new scheduler_1.MeghScheduler();
|
|
146
148
|
schedulerTasks = [];
|
|
147
149
|
registerSchedulerAuto = false;
|
|
@@ -153,9 +155,22 @@ class MeghApplication {
|
|
|
153
155
|
close: [],
|
|
154
156
|
};
|
|
155
157
|
closing = null;
|
|
158
|
+
signalHandler = null;
|
|
156
159
|
pluginNames = [];
|
|
160
|
+
usesCache = false;
|
|
161
|
+
health = new health_1.HealthRegistry();
|
|
162
|
+
errorHandler = new errors_1.MeghErrorHandler({
|
|
163
|
+
isDevelopment: () => this.isDevelopment(),
|
|
164
|
+
});
|
|
157
165
|
constructor(options) {
|
|
166
|
+
const requestId = options?.requestId ?? {};
|
|
167
|
+
const requestIdHeader = (requestId && requestId.header) || request_context_1.DEFAULT_REQUEST_ID_HEADER;
|
|
158
168
|
this.app = (0, fastify_1.default)({
|
|
169
|
+
...(requestId && {
|
|
170
|
+
// genReqId decides; Fastify's own header lookup would trust any value.
|
|
171
|
+
requestIdHeader: false,
|
|
172
|
+
genReqId: (0, request_context_1.createRequestIdGenerator)(requestIdHeader, requestId.generate),
|
|
173
|
+
}),
|
|
159
174
|
...options?.server,
|
|
160
175
|
ajv: {
|
|
161
176
|
customOptions: {
|
|
@@ -164,7 +179,12 @@ class MeghApplication {
|
|
|
164
179
|
},
|
|
165
180
|
},
|
|
166
181
|
});
|
|
167
|
-
this.router = new router_1.MeghRouter(this.app
|
|
182
|
+
this.router = new router_1.MeghRouter(this.app, {
|
|
183
|
+
compiledValidation: options?.experimental?.compiledValidation ??
|
|
184
|
+
/^(1|true)$/i.test(process.env.MEGH_COMPILED_VALIDATION ?? ""),
|
|
185
|
+
});
|
|
186
|
+
if (requestId)
|
|
187
|
+
(0, request_context_1.installRequestContext)(this.app, requestIdHeader);
|
|
168
188
|
this.pluginNames = (0, registry_1.registerPlugins)(this, options);
|
|
169
189
|
if (this.pluginNames.length) {
|
|
170
190
|
(0, internal_logger_1.internalLogger)("plugins").info({ plugins: this.pluginNames }, "Plugins registered");
|
|
@@ -191,6 +211,7 @@ class MeghApplication {
|
|
|
191
211
|
}
|
|
192
212
|
useCache(options) {
|
|
193
213
|
cache_1.CacheManager.configure(options);
|
|
214
|
+
this.usesCache = true;
|
|
194
215
|
if (!di_1.Container.has(cache_1.CacheManager)) {
|
|
195
216
|
di_1.Container.set(cache_1.CacheManager, new cache_1.CacheManager());
|
|
196
217
|
}
|
|
@@ -292,6 +313,10 @@ class MeghApplication {
|
|
|
292
313
|
middlewares.forEach((m) => {
|
|
293
314
|
const cls = di_1.Container.get(m);
|
|
294
315
|
this.app.addHook("preHandler", async (req, res) => {
|
|
316
|
+
// Health probes must answer even when global middleware would reject
|
|
317
|
+
// the request (an API key check, an IP allowlist).
|
|
318
|
+
if (req.routeOptions?.config?.[health_1.SKIP_GLOBAL_MIDDLEWARE])
|
|
319
|
+
return;
|
|
295
320
|
await cls.invoke(req, res);
|
|
296
321
|
});
|
|
297
322
|
});
|
|
@@ -338,7 +363,69 @@ class MeghApplication {
|
|
|
338
363
|
}
|
|
339
364
|
return this;
|
|
340
365
|
}
|
|
341
|
-
|
|
366
|
+
/**
|
|
367
|
+
* Register global exception filters. They run in order, after any
|
|
368
|
+
* `@UseFilters` on the route or controller, and before Megh's default
|
|
369
|
+
* error response.
|
|
370
|
+
*
|
|
371
|
+
* app.useExceptionFilters([EntityNotFoundFilter, ProblemJsonFilter])
|
|
372
|
+
*
|
|
373
|
+
* Each entry can be a filter class (resolved through DI), a filter
|
|
374
|
+
* instance or a function `(error, ctx) => ...`.
|
|
375
|
+
*
|
|
376
|
+
* @see ExceptionFilter
|
|
377
|
+
*/
|
|
378
|
+
useExceptionFilters(filters) {
|
|
379
|
+
this.assertNotStarted("useExceptionFilters");
|
|
380
|
+
this.errorHandler.addFilters(Array.isArray(filters) ? filters : [filters]);
|
|
381
|
+
return this;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Register a function that handles request errors. It is a global filter
|
|
385
|
+
* that sees every error: return a body to send it, return an `Error` to
|
|
386
|
+
* hand it on, or return nothing to fall back to the default response.
|
|
387
|
+
*
|
|
388
|
+
* app.useErrorHandler((error, { response }) => ({
|
|
389
|
+
* ok: false,
|
|
390
|
+
* message: response.body.message,
|
|
391
|
+
* }))
|
|
392
|
+
*/
|
|
393
|
+
useErrorHandler(handler) {
|
|
394
|
+
return this.useExceptionFilters([handler]);
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Replace how errors answered with the default response are logged, or
|
|
398
|
+
* pass `false` to stop logging them.
|
|
399
|
+
*/
|
|
400
|
+
useErrorLogger(logger) {
|
|
401
|
+
this.errorHandler.setLogger(logger);
|
|
402
|
+
return this;
|
|
403
|
+
}
|
|
404
|
+
/** Install the error and not-found handlers on the Fastify instance. @internal */
|
|
405
|
+
installErrorHandling() {
|
|
406
|
+
this.errorHandler.install(this.app);
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Serve health routes: `GET /health` (liveness, always 200) and
|
|
410
|
+
* `GET /ready` (readiness: runs every health check, 503 if one fails).
|
|
411
|
+
* Plugins register their own checks, such as Megh ORM's `database`.
|
|
412
|
+
*
|
|
413
|
+
* app.useHealth({ checks: { redis: () => redis.ping() } })
|
|
414
|
+
*/
|
|
415
|
+
useHealth(options = {}) {
|
|
416
|
+
this.assertNotStarted("useHealth");
|
|
417
|
+
for (const [name, check] of Object.entries(options.checks ?? {})) {
|
|
418
|
+
this.health.add(name, check);
|
|
419
|
+
}
|
|
420
|
+
this.health.install(this.app, options, () => this.isDevelopment());
|
|
421
|
+
return this;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Add a readiness check, reported by `GET /ready` once `useHealth()` is on.
|
|
425
|
+
* It passes unless it throws, rejects or returns `false`.
|
|
426
|
+
*/
|
|
427
|
+
addHealthCheck(name, check) {
|
|
428
|
+
this.health.add(name, check);
|
|
342
429
|
return this;
|
|
343
430
|
}
|
|
344
431
|
/**
|
|
@@ -383,9 +470,6 @@ class MeghApplication {
|
|
|
383
470
|
this.app.register(requireStatic(), options); // ✅ lazy
|
|
384
471
|
return this;
|
|
385
472
|
}
|
|
386
|
-
useHttps(options) {
|
|
387
|
-
return this;
|
|
388
|
-
}
|
|
389
473
|
useGlobal(options) {
|
|
390
474
|
if (options.cors)
|
|
391
475
|
this.useCors(options.cors);
|
|
@@ -442,15 +526,11 @@ class MeghApplication {
|
|
|
442
526
|
await w?.close?.();
|
|
443
527
|
}
|
|
444
528
|
catch (err) {
|
|
445
|
-
|
|
529
|
+
(0, internal_logger_1.internalLogger)("queue").error({ err }, "Failed to close worker");
|
|
446
530
|
}
|
|
447
531
|
}));
|
|
448
532
|
this._workers = [];
|
|
449
533
|
}
|
|
450
|
-
mapFeatures() {
|
|
451
|
-
this.isMapFeatures = true;
|
|
452
|
-
return this;
|
|
453
|
-
}
|
|
454
534
|
/**
|
|
455
535
|
* True only when `NODE_ENV` is exactly `"development"`. An unset
|
|
456
536
|
* `NODE_ENV` counts as production, so dev-only features (API docs,
|
|
@@ -476,8 +556,7 @@ class MeghApplication {
|
|
|
476
556
|
const isTsNode = process.env.TS_NODE_DEV ||
|
|
477
557
|
process.env.TS_NODE_PROJECT ||
|
|
478
558
|
process[Symbol.for("ts-node.register.instance")];
|
|
479
|
-
|
|
480
|
-
return isTsNode ? controllerDir : controllerDir.replace("src", "dist");
|
|
559
|
+
return (0, path_utils_1.resolveSourceDir)(dir ?? this.registerControllerPath, !!isTsNode);
|
|
481
560
|
}
|
|
482
561
|
async autoControllers(controllersPath) {
|
|
483
562
|
const conDir = this._resolveControllerDir(controllersPath);
|
|
@@ -507,15 +586,7 @@ class MeghApplication {
|
|
|
507
586
|
}
|
|
508
587
|
}
|
|
509
588
|
catch (e) {
|
|
510
|
-
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
_mapFeatures() {
|
|
514
|
-
try {
|
|
515
|
-
di_1.Container.get("features");
|
|
516
|
-
}
|
|
517
|
-
catch {
|
|
518
|
-
// features token not registered — safe to ignore
|
|
589
|
+
(0, internal_logger_1.internalLogger)("app").warn({ err: e, dir: conDir }, "Could not auto-register controllers");
|
|
519
590
|
}
|
|
520
591
|
}
|
|
521
592
|
handleSocket(socket) {
|
|
@@ -523,7 +594,6 @@ class MeghApplication {
|
|
|
523
594
|
try {
|
|
524
595
|
const { SocketContextService } = require("../events/socket-dispatcher");
|
|
525
596
|
const { EventSubscriberRegistry } = require("../events/event-subscriber");
|
|
526
|
-
const { SocketIoServer } = require("../realtime/websocket");
|
|
527
597
|
const contextService = di_1.Container.get(SocketContextService);
|
|
528
598
|
const subscriberRegistry = di_1.Container.get(EventSubscriberRegistry);
|
|
529
599
|
subscriberRegistry.register(socket);
|
|
@@ -535,7 +605,7 @@ class MeghApplication {
|
|
|
535
605
|
};
|
|
536
606
|
}
|
|
537
607
|
catch (e) {
|
|
538
|
-
|
|
608
|
+
(0, internal_logger_1.internalLogger)("realtime").warn({ err: e }, "Socket handler error");
|
|
539
609
|
}
|
|
540
610
|
}
|
|
541
611
|
// ── Functional routing proxies ───────────────────────────────────────────
|
|
@@ -548,6 +618,9 @@ class MeghApplication {
|
|
|
548
618
|
mapPut(path = "", fn) {
|
|
549
619
|
return this.router.mapPut(path, fn);
|
|
550
620
|
}
|
|
621
|
+
mapPatch(path = "", fn) {
|
|
622
|
+
return this.router.mapPatch(path, fn);
|
|
623
|
+
}
|
|
551
624
|
mapDelete(path = "", fn) {
|
|
552
625
|
return this.router.mapDelete(path, fn);
|
|
553
626
|
}
|
|
@@ -586,15 +659,28 @@ class MeghApplication {
|
|
|
586
659
|
return this.closing;
|
|
587
660
|
}
|
|
588
661
|
async _close() {
|
|
662
|
+
if (this.signalHandler) {
|
|
663
|
+
process.removeListener("SIGTERM", this.signalHandler);
|
|
664
|
+
process.removeListener("SIGINT", this.signalHandler);
|
|
665
|
+
this.signalHandler = null;
|
|
666
|
+
}
|
|
589
667
|
await this.app.close();
|
|
590
668
|
this.scheduler.stopAll();
|
|
591
669
|
await this._closeWorkers();
|
|
670
|
+
if (this.usesCache) {
|
|
671
|
+
try {
|
|
672
|
+
await cache_1.CacheManager.close();
|
|
673
|
+
}
|
|
674
|
+
catch (err) {
|
|
675
|
+
(0, internal_logger_1.internalLogger)("app").error({ err }, "Closing the cache failed");
|
|
676
|
+
}
|
|
677
|
+
}
|
|
592
678
|
for (const hook of [...this.lifecycleHooks.close].reverse()) {
|
|
593
679
|
try {
|
|
594
680
|
await hook();
|
|
595
681
|
}
|
|
596
682
|
catch (err) {
|
|
597
|
-
|
|
683
|
+
(0, internal_logger_1.internalLogger)("app").error({ err }, "onClose hook failed");
|
|
598
684
|
}
|
|
599
685
|
}
|
|
600
686
|
}
|
|
@@ -615,9 +701,7 @@ class MeghApplication {
|
|
|
615
701
|
process[Symbol.for("ts-node.register.instance")];
|
|
616
702
|
const nodePath = require("path");
|
|
617
703
|
const nodeFs = require("fs");
|
|
618
|
-
const
|
|
619
|
-
const dir = nodePath.join(process.cwd(), this.registerSchedulerPath);
|
|
620
|
-
const resolvedDir = isTsNode ? dir : dir.replace("src", "dist");
|
|
704
|
+
const resolvedDir = (0, path_utils_1.resolveSourceDir)(this.registerSchedulerPath, !!isTsNode);
|
|
621
705
|
try {
|
|
622
706
|
const files = nodeFs.readdirSync(resolvedDir, {
|
|
623
707
|
recursive: true,
|
|
@@ -630,7 +714,7 @@ class MeghApplication {
|
|
|
630
714
|
if (isTsNode ? file.endsWith(".ts") : file.endsWith(".js")) {
|
|
631
715
|
const mod = await Promise.resolve(`${nodePath.join(resolvedDir, file)}`).then(s => __importStar(require(s)));
|
|
632
716
|
for (const exported of Object.values(mod)) {
|
|
633
|
-
if (typeof exported === "function" && isScheduledTask(exported)) {
|
|
717
|
+
if (typeof exported === "function" && (0, schedule_registry_1.isScheduledTask)(exported)) {
|
|
634
718
|
if (!this.schedulerTasks.some((t) => t.name === exported.name)) {
|
|
635
719
|
this.schedulerTasks.push(exported);
|
|
636
720
|
this.scheduler.addTaskClasses([exported]);
|
|
@@ -641,20 +725,30 @@ class MeghApplication {
|
|
|
641
725
|
}
|
|
642
726
|
}
|
|
643
727
|
catch (e) {
|
|
644
|
-
|
|
728
|
+
(0, internal_logger_1.internalLogger)("scheduler").warn({ err: e, dir: resolvedDir }, "Could not auto-register tasks");
|
|
645
729
|
}
|
|
646
730
|
}
|
|
647
|
-
|
|
731
|
+
/**
|
|
732
|
+
* Start the server.
|
|
733
|
+
*
|
|
734
|
+
* await app.run(3000)
|
|
735
|
+
* await app.run(3000, { host: "127.0.0.1" })
|
|
736
|
+
*
|
|
737
|
+
* The port defaults to the `PORT` environment variable, else `4000`. The
|
|
738
|
+
* host defaults to the `HOST` environment variable, else `0.0.0.0` so the
|
|
739
|
+
* app is reachable inside containers.
|
|
740
|
+
*/
|
|
741
|
+
async run(port, options) {
|
|
742
|
+
const fn = typeof options === "function" ? options : options?.onListen;
|
|
743
|
+
const runOptions = typeof options === "object" ? options : {};
|
|
648
744
|
if (this.alreadyRun)
|
|
649
745
|
throw new system_exception_1.SystemUseError("App already running");
|
|
746
|
+
const listenPort = port ?? portFromEnv();
|
|
650
747
|
this.alreadyRun = true;
|
|
651
748
|
if (this.hasSwagger) {
|
|
652
749
|
await this.initSwagger(this.globalSwaggerOptions);
|
|
653
750
|
}
|
|
654
751
|
await this.runHooks(this.lifecycleHooks.init);
|
|
655
|
-
if (this.isMapFeatures) {
|
|
656
|
-
this._mapFeatures();
|
|
657
|
-
}
|
|
658
752
|
if (this.registerControllerAuto) {
|
|
659
753
|
await this.autoControllers();
|
|
660
754
|
}
|
|
@@ -668,64 +762,7 @@ class MeghApplication {
|
|
|
668
762
|
if (this.schedulerTasks.length > 0) {
|
|
669
763
|
this.scheduler.start();
|
|
670
764
|
}
|
|
671
|
-
this.
|
|
672
|
-
const isDev = this.isDevelopment();
|
|
673
|
-
const timestamp = new Date().toISOString();
|
|
674
|
-
const requestInfo = `${request.method} ${request.url}`;
|
|
675
|
-
// ✅ Handle Fastify AJV validation errors — these come with statusCode 400
|
|
676
|
-
if (error.statusCode === 400 || error.validation) {
|
|
677
|
-
console.warn(`[${timestamp}] HTTP 400 ${requestInfo} — ${error.message}`);
|
|
678
|
-
return reply.status(400).send({
|
|
679
|
-
code: 400,
|
|
680
|
-
status: "Error",
|
|
681
|
-
message: error.message,
|
|
682
|
-
errors: error.validation ?? undefined,
|
|
683
|
-
});
|
|
684
|
-
}
|
|
685
|
-
if (error instanceof exceptions_1.BaseHttpException) {
|
|
686
|
-
const code = error.code || 500;
|
|
687
|
-
console.warn(`[${timestamp}] HTTP ${code} ${requestInfo} — ${error.message}`);
|
|
688
|
-
// 4xx messages are written for the client; 5xx ones describe server
|
|
689
|
-
// internals and are only shown in development.
|
|
690
|
-
const expose = isDev || code < 500;
|
|
691
|
-
return reply
|
|
692
|
-
.status(code)
|
|
693
|
-
.type("application/json")
|
|
694
|
-
.serializer((payload) => JSON.stringify(payload))
|
|
695
|
-
.send({
|
|
696
|
-
code,
|
|
697
|
-
status: "Error",
|
|
698
|
-
message: expose ? error.message : "Internal Server Error",
|
|
699
|
-
...(expose && { data: error.payload }),
|
|
700
|
-
});
|
|
701
|
-
}
|
|
702
|
-
// Unexpected errors
|
|
703
|
-
console.error(`\n❌ UNHANDLED ERROR @ ${timestamp}`);
|
|
704
|
-
console.error(` ${requestInfo}`);
|
|
705
|
-
console.error(` ${error.name}: ${error.message}`);
|
|
706
|
-
if (error.stack) {
|
|
707
|
-
console.error(` Stack:\n${error.stack
|
|
708
|
-
.split("\n")
|
|
709
|
-
.slice(1)
|
|
710
|
-
.map((l) => ` ${l.trim()}`)
|
|
711
|
-
.join("\n")}`);
|
|
712
|
-
}
|
|
713
|
-
if (isDev) {
|
|
714
|
-
console.error(" Params:", JSON.stringify(request.params));
|
|
715
|
-
console.error(" Query: ", JSON.stringify(request.query));
|
|
716
|
-
console.error(" Body: ", JSON.stringify(request.body));
|
|
717
|
-
}
|
|
718
|
-
console.error("");
|
|
719
|
-
return reply.status(500).send({
|
|
720
|
-
code: 500,
|
|
721
|
-
status: "Error",
|
|
722
|
-
message: isDev ? error.message : "Internal Server Error",
|
|
723
|
-
...(isDev && {
|
|
724
|
-
error: error.name,
|
|
725
|
-
stack: error.stack?.split("\n").slice(0, 5),
|
|
726
|
-
}),
|
|
727
|
-
});
|
|
728
|
-
});
|
|
765
|
+
this.installErrorHandling();
|
|
729
766
|
await this.app.ready();
|
|
730
767
|
if (this._hasWebsocket) {
|
|
731
768
|
// @ts-ignore
|
|
@@ -741,23 +778,52 @@ class MeghApplication {
|
|
|
741
778
|
await this.app.io.on("connection", this.handleSocket.bind(this));
|
|
742
779
|
}
|
|
743
780
|
catch (e) {
|
|
744
|
-
|
|
781
|
+
(0, internal_logger_1.internalLogger)("realtime").warn({ err: e }, "WebSocket setup error");
|
|
745
782
|
}
|
|
746
783
|
}
|
|
747
|
-
const
|
|
748
|
-
|
|
749
|
-
|
|
784
|
+
const timeout = runOptions.shutdownTimeout ?? 10_000;
|
|
785
|
+
const gracefulStop = async (signal) => {
|
|
786
|
+
const log = (0, internal_logger_1.internalLogger)("app");
|
|
787
|
+
log.info({ signal }, "Shutting down");
|
|
788
|
+
// A hung close (open keep-alive sockets, a stuck hook) must not keep
|
|
789
|
+
// the process alive forever.
|
|
790
|
+
const timer = setTimeout(() => {
|
|
791
|
+
log.error({ timeout }, "Shutdown timed out; exiting");
|
|
792
|
+
process.exit(1);
|
|
793
|
+
}, timeout);
|
|
794
|
+
timer.unref();
|
|
795
|
+
try {
|
|
796
|
+
await this.close();
|
|
797
|
+
process.exit(0);
|
|
798
|
+
}
|
|
799
|
+
catch (err) {
|
|
800
|
+
log.error({ err }, "Shutdown failed");
|
|
801
|
+
process.exit(1);
|
|
802
|
+
}
|
|
750
803
|
};
|
|
804
|
+
this.signalHandler = gracefulStop;
|
|
751
805
|
process.once("SIGTERM", gracefulStop);
|
|
752
806
|
process.once("SIGINT", gracefulStop);
|
|
753
|
-
|
|
754
|
-
|
|
807
|
+
const host = runOptions.host ?? process.env.HOST ?? "0.0.0.0";
|
|
808
|
+
const address = await this.app.listen({ port: listenPort, host });
|
|
809
|
+
(0, internal_logger_1.internalLogger)("app").info({ address }, `Application running on ${address}`);
|
|
755
810
|
await this.runHooks(this.lifecycleHooks.ready);
|
|
756
811
|
if (fn)
|
|
757
812
|
fn();
|
|
758
813
|
}
|
|
759
814
|
}
|
|
760
815
|
exports.MeghApplication = MeghApplication;
|
|
816
|
+
/** The port from the `PORT` environment variable, else 4000. */
|
|
817
|
+
function portFromEnv() {
|
|
818
|
+
const raw = process.env.PORT?.trim();
|
|
819
|
+
if (!raw)
|
|
820
|
+
return 4000;
|
|
821
|
+
const port = Number(raw);
|
|
822
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
823
|
+
throw new system_exception_1.SystemUseError(`Invalid PORT "${process.env.PORT}": expected a whole number from 0 to 65535.`);
|
|
824
|
+
}
|
|
825
|
+
return port;
|
|
826
|
+
}
|
|
761
827
|
/** The security scheme and requirement for `useOpenApi({ auth })`. */
|
|
762
828
|
function openApiSecurity(auth) {
|
|
763
829
|
if (!auth)
|