@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.
Files changed (110) hide show
  1. package/README.md +54 -137
  2. package/dist/common/container.js +0 -1
  3. package/dist/common/container.js.map +1 -1
  4. package/dist/common/exceptions/http-exceptions.d.ts +1 -50
  5. package/dist/common/exceptions/http-exceptions.js +15 -80
  6. package/dist/common/exceptions/http-exceptions.js.map +1 -1
  7. package/dist/common/exceptions/system-exception.d.ts +0 -10
  8. package/dist/common/exceptions/system-exception.js +7 -12
  9. package/dist/common/exceptions/system-exception.js.map +1 -1
  10. package/dist/common/utils/compiled-validation.d.ts +43 -0
  11. package/dist/common/utils/compiled-validation.js +299 -0
  12. package/dist/common/utils/compiled-validation.js.map +1 -0
  13. package/dist/common/utils/object-utils.d.ts +4 -0
  14. package/dist/common/utils/object-utils.js +44 -7
  15. package/dist/common/utils/object-utils.js.map +1 -1
  16. package/dist/common/utils/path-utils.d.ts +7 -0
  17. package/dist/common/utils/path-utils.js +15 -0
  18. package/dist/common/utils/path-utils.js.map +1 -1
  19. package/dist/config/environment-variables.d.ts +2 -0
  20. package/dist/config/environment-variables.js +24 -12
  21. package/dist/config/environment-variables.js.map +1 -1
  22. package/dist/core/application.d.ts +90 -12
  23. package/dist/core/application.js +166 -100
  24. package/dist/core/application.js.map +1 -1
  25. package/dist/core/interfaces.d.ts +48 -4
  26. package/dist/core/router.d.ts +59 -9
  27. package/dist/core/router.js +233 -123
  28. package/dist/core/router.js.map +1 -1
  29. package/dist/core/testing.js +2 -12
  30. package/dist/core/testing.js.map +1 -1
  31. package/dist/core/types.d.ts +6 -0
  32. package/dist/errors/error-handler.d.ts +56 -0
  33. package/dist/errors/error-handler.js +206 -0
  34. package/dist/errors/error-handler.js.map +1 -0
  35. package/dist/errors/exception-filter.d.ts +96 -0
  36. package/dist/errors/exception-filter.js +68 -0
  37. package/dist/errors/exception-filter.js.map +1 -0
  38. package/dist/errors/http-exceptions.d.ts +413 -0
  39. package/dist/errors/http-exceptions.js +155 -0
  40. package/dist/errors/http-exceptions.js.map +1 -0
  41. package/dist/errors/index.d.ts +4 -0
  42. package/dist/errors/index.js +24 -0
  43. package/dist/errors/index.js.map +1 -0
  44. package/dist/events/event-subscriber.js +14 -3
  45. package/dist/events/event-subscriber.js.map +1 -1
  46. package/dist/events/socket-dispatcher.d.ts +1 -3
  47. package/dist/events/socket-dispatcher.js +2 -10
  48. package/dist/events/socket-dispatcher.js.map +1 -1
  49. package/dist/http/multipart.js.map +1 -1
  50. package/dist/http/params.js +3 -1
  51. package/dist/http/params.js.map +1 -1
  52. package/dist/http/route-methods.js.map +1 -1
  53. package/dist/http/validator-extend.js +1 -1
  54. package/dist/http/validator-extend.js.map +1 -1
  55. package/dist/index.d.ts +3 -2
  56. package/dist/index.js +7 -3
  57. package/dist/index.js.map +1 -1
  58. package/dist/observability/health.d.ts +45 -0
  59. package/dist/observability/health.js +74 -0
  60. package/dist/observability/health.js.map +1 -0
  61. package/dist/observability/index.d.ts +3 -0
  62. package/dist/observability/index.js +5 -0
  63. package/dist/observability/index.js.map +1 -1
  64. package/dist/observability/logger.js +8 -1
  65. package/dist/observability/logger.js.map +1 -1
  66. package/dist/observability/request-context.d.ts +29 -0
  67. package/dist/observability/request-context.js +54 -0
  68. package/dist/observability/request-context.js.map +1 -0
  69. package/dist/openapi/swagger-schema.d.ts +0 -2
  70. package/dist/openapi/swagger-schema.js +21 -5
  71. package/dist/openapi/swagger-schema.js.map +1 -1
  72. package/dist/orm/connect.d.ts +2 -0
  73. package/dist/orm/connect.js +6 -1
  74. package/dist/orm/connect.js.map +1 -1
  75. package/dist/orm/plugin.js +2 -0
  76. package/dist/orm/plugin.js.map +1 -1
  77. package/dist/plugins/plugin.d.ts +3 -0
  78. package/dist/plugins/plugin.js.map +1 -1
  79. package/dist/plugins/registry.js +1 -0
  80. package/dist/plugins/registry.js.map +1 -1
  81. package/dist/realtime/websocket.d.ts +1 -7
  82. package/dist/realtime/websocket.js +2 -18
  83. package/dist/realtime/websocket.js.map +1 -1
  84. package/dist/storage/file-storage.js +6 -4
  85. package/dist/storage/file-storage.js.map +1 -1
  86. package/dist/validator/compat.d.ts +5 -0
  87. package/dist/validator/compat.js +42 -0
  88. package/dist/validator/compat.js.map +1 -0
  89. package/dist/validator/compiler.d.ts +20 -0
  90. package/dist/validator/compiler.js +219 -0
  91. package/dist/validator/compiler.js.map +1 -0
  92. package/dist/validator/decorators.d.ts +81 -0
  93. package/dist/validator/decorators.js +377 -0
  94. package/dist/validator/decorators.js.map +1 -0
  95. package/dist/validator/index.d.ts +16 -0
  96. package/dist/validator/index.js +36 -0
  97. package/dist/validator/index.js.map +1 -0
  98. package/dist/validator/is-email.d.ts +25 -0
  99. package/dist/validator/is-email.js +204 -0
  100. package/dist/validator/is-email.js.map +1 -0
  101. package/dist/validator/messages.d.ts +20 -0
  102. package/dist/validator/messages.js +186 -0
  103. package/dist/validator/messages.js.map +1 -0
  104. package/dist/validator/metadata.d.ts +118 -0
  105. package/dist/validator/metadata.js +153 -0
  106. package/dist/validator/metadata.js.map +1 -0
  107. package/dist/validator/transform.d.ts +29 -0
  108. package/dist/validator/transform.js +210 -0
  109. package/dist/validator/transform.js.map +1 -0
  110. package/package.json +8 -3
@@ -9,7 +9,6 @@ exports.Megh = exports.MeghTest = void 0;
9
9
  */
10
10
  const application_1 = require("./application");
11
11
  const di_1 = require("../di");
12
- const exceptions_1 = require("../common/exceptions");
13
12
  const system_exception_1 = require("../common/exceptions/system-exception");
14
13
  class MeghTest {
15
14
  constructor() {
@@ -54,17 +53,8 @@ class MeghTest {
54
53
  // In icore.ts, it was mapping routes to app.route explicitly.
55
54
  // In our refactor, _mapControllers calls router.buildController -> which adds routes to app.
56
55
  // So fastify app should be ready.
57
- app.app.setErrorHandler(async (error, req, res) => {
58
- // Reuse error handler logic or simplified version
59
- if (error instanceof exceptions_1.ValidationErrorException) {
60
- return res.status(400).send({
61
- code: 400,
62
- error: "ValidationError",
63
- errors: error.message,
64
- });
65
- }
66
- return res.status(500).send(error);
67
- });
56
+ // Same error handling as production, filters included.
57
+ app.installErrorHandling();
68
58
  return {
69
59
  get: async (url, options) => app.app.inject({ method: "GET", url, ...options }),
70
60
  post: async (url, options) => app.app.inject({ method: "POST", url, ...options }),
@@ -1 +1 @@
1
- {"version":3,"file":"testing.js","sourceRoot":"","sources":["../../src/core/testing.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,+CAAgD;AAChD,8BAAkC;AAQlC,qDAAgE;AAChE,4EAAuE;AAEvE,MAAa,QAAQ;IACnB;QACE,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,MAAM,CAAC;IAChC,CAAC;IAED,MAAM,CAAC,aAAa,CAAI,UAA0B,EAAE,OAAc,EAAE;QAClE,MAAM,UAAU,GACd,OAAO,CAAC,WAAW,CAAC,mBAAmB,EAAE,UAAU,CAAC,IAAI,EAAE,CAAC;QAE7D,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;YACtB,cAAS,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;QACpC,CAAC,CAAC,CAAC;QAEH,OAAO,cAAS,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACnC,CAAC;IAED,MAAM,CAAC,WAAW,CAAI,OAAuB,EAAE,OAAc,EAAE;QAC7D,MAAM,UAAU,GAAG,OAAO,CAAC,WAAW,CAAC,mBAAmB,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;QAE3E,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;YACtB,cAAS,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;QACpC,CAAC,CAAC,CAAC;QAEH,OAAO,cAAS,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IAED,MAAM,CAAC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;QAClD,MAAM,GAAG,GAAG,QAAQ,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;QACpD,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AATD,oBASC"}
@@ -58,8 +58,14 @@ export interface IRoute {
58
58
  }
59
59
  export type FuncRoute = {
60
60
  handler: Function;
61
+ /** Middleware classes or instances, resolved when routes are mapped. */
61
62
  middlewares: any[];
62
63
  schema: any;
64
+ /** Set by `.authorized()`: the `@Authorized` options for this route. */
65
+ authorize?: {
66
+ name?: string;
67
+ [key: string]: unknown;
68
+ };
63
69
  };
64
70
  export type StaticFileOptions = {
65
71
  path?: string;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
8
+ import { ErrorHandlerFunction, ErrorResponse, ExceptionFilterLike } from "./exception-filter";
9
+ /** Route config key holding the filters from `@UseFilters`. */
10
+ export declare const ROUTE_FILTERS_CONFIG_KEY = "meghExceptionFilters";
11
+ /** A filter normalised to a function plus the error classes it accepts. */
12
+ export interface ResolvedFilter {
13
+ types: Function[];
14
+ run: ErrorHandlerFunction;
15
+ }
16
+ /**
17
+ * The response Megh sends for `error` when no filter handles it.
18
+ *
19
+ * - `HttpException`s keep their status. Their message and payload are sent
20
+ * for 4xx; for 5xx only in development.
21
+ * - Fastify's request validation errors become 400 with the AJV issues.
22
+ * - Other errors with a 4xx/5xx `statusCode` (body too large, unsupported
23
+ * media type, rate limited...) keep that status.
24
+ * - Anything else is a 500 whose details only show in development.
25
+ */
26
+ export declare function defaultErrorResponse(error: any, isDevelopment: boolean): ErrorResponse;
27
+ /** Turn a filter class, instance or function into a {@link ResolvedFilter}. */
28
+ export declare function resolveFilter(filter: ExceptionFilterLike): ResolvedFilter;
29
+ export type ErrorLogger = (error: unknown, request: FastifyRequest, response: ErrorResponse) => void;
30
+ /** Logs 4xx as warnings and everything else as errors with the stack. */
31
+ export declare const defaultErrorLogger: ErrorLogger;
32
+ export interface ErrorHandlerOptions {
33
+ /** Return true to expose 5xx details. Defaults to `NODE_ENV === "development"`. */
34
+ isDevelopment?: () => boolean;
35
+ /** Logs errors answered with the default response. `false` turns it off. */
36
+ logger?: ErrorLogger | false;
37
+ }
38
+ /**
39
+ * Megh's request error handler: runs the exception filters in order, then
40
+ * falls back to {@link defaultErrorResponse}.
41
+ *
42
+ * Order: `@UseFilters` on the route, on the controller, then the global
43
+ * filters in registration order.
44
+ */
45
+ export declare class MeghErrorHandler {
46
+ private readonly globalFilters;
47
+ private readonly isDevelopment;
48
+ private logger;
49
+ constructor(options?: ErrorHandlerOptions);
50
+ /** Append global filters. */
51
+ addFilters(filters: ExceptionFilterLike[]): this;
52
+ setLogger(logger: ErrorLogger | false): this;
53
+ /** Install on a Fastify instance as its error and not-found handler. */
54
+ install(app: FastifyInstance): void;
55
+ handle(error: unknown, request: FastifyRequest, reply: FastifyReply): Promise<never>;
56
+ }
@@ -0,0 +1,206 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MeghErrorHandler = exports.defaultErrorLogger = exports.ROUTE_FILTERS_CONFIG_KEY = void 0;
4
+ exports.defaultErrorResponse = defaultErrorResponse;
5
+ exports.resolveFilter = resolveFilter;
6
+ const di_1 = require("../di");
7
+ const internal_logger_1 = require("../observability/internal-logger");
8
+ const http_exceptions_1 = require("./http-exceptions");
9
+ const exception_filter_1 = require("./exception-filter");
10
+ /** Route config key holding the filters from `@UseFilters`. */
11
+ exports.ROUTE_FILTERS_CONFIG_KEY = "meghExceptionFilters";
12
+ const GENERIC_5XX = "Internal Server Error";
13
+ function statusOf(error) {
14
+ const status = error?.statusCode ?? error?.status;
15
+ return Number.isInteger(status) && status >= 400 && status <= 599
16
+ ? status
17
+ : undefined;
18
+ }
19
+ /**
20
+ * The response Megh sends for `error` when no filter handles it.
21
+ *
22
+ * - `HttpException`s keep their status. Their message and payload are sent
23
+ * for 4xx; for 5xx only in development.
24
+ * - Fastify's request validation errors become 400 with the AJV issues.
25
+ * - Other errors with a 4xx/5xx `statusCode` (body too large, unsupported
26
+ * media type, rate limited...) keep that status.
27
+ * - Anything else is a 500 whose details only show in development.
28
+ */
29
+ function defaultErrorResponse(error, isDevelopment) {
30
+ if (error instanceof http_exceptions_1.BaseHttpException) {
31
+ const statusCode = error.code || 500;
32
+ const expose = isDevelopment || statusCode < 500;
33
+ const body = {
34
+ code: statusCode,
35
+ status: "Error",
36
+ message: expose ? error.message : GENERIC_5XX,
37
+ };
38
+ if (error instanceof http_exceptions_1.ValidationErrorException && error.errors) {
39
+ body.errors = error.errors;
40
+ }
41
+ else if (expose && error.payload !== undefined) {
42
+ body.data = error.payload;
43
+ }
44
+ return { statusCode, headers: error.headers, body };
45
+ }
46
+ if (error?.validation) {
47
+ const statusCode = statusOf(error) ?? 400;
48
+ return {
49
+ statusCode,
50
+ body: {
51
+ code: statusCode,
52
+ status: "Error",
53
+ message: error.message,
54
+ errors: error.validation,
55
+ },
56
+ };
57
+ }
58
+ const known = statusOf(error);
59
+ if (known !== undefined) {
60
+ const expose = isDevelopment || known < 500;
61
+ return {
62
+ statusCode: known,
63
+ body: {
64
+ code: known,
65
+ status: "Error",
66
+ message: expose ? String(error.message ?? "") : GENERIC_5XX,
67
+ },
68
+ };
69
+ }
70
+ return {
71
+ statusCode: 500,
72
+ body: {
73
+ code: 500,
74
+ status: "Error",
75
+ message: isDevelopment ? String(error?.message ?? error) : GENERIC_5XX,
76
+ ...(isDevelopment && {
77
+ error: error?.name,
78
+ stack: error?.stack?.split("\n").slice(0, 5),
79
+ }),
80
+ },
81
+ };
82
+ }
83
+ /** Turn a filter class, instance or function into a {@link ResolvedFilter}. */
84
+ function resolveFilter(filter) {
85
+ if (typeof filter === "function") {
86
+ if (typeof filter.prototype?.catch === "function") {
87
+ const instance = di_1.Container.get(filter);
88
+ return {
89
+ types: Reflect.getMetadata(exception_filter_1.CATCH_META_KEY, filter) ?? [],
90
+ run: (error, ctx) => instance.catch(error, ctx),
91
+ };
92
+ }
93
+ return { types: [], run: filter };
94
+ }
95
+ if (filter && typeof filter.catch === "function") {
96
+ return {
97
+ types: Reflect.getMetadata(exception_filter_1.CATCH_META_KEY, filter.constructor) ?? [],
98
+ run: (error, ctx) => filter.catch(error, ctx),
99
+ };
100
+ }
101
+ throw new TypeError("[Megh] An exception filter must be a class or object with a catch() method, or a function.");
102
+ }
103
+ function accepts(filter, error) {
104
+ return (filter.types.length === 0 ||
105
+ filter.types.some((t) => error instanceof t));
106
+ }
107
+ /** Logs 4xx as warnings and everything else as errors with the stack. */
108
+ const defaultErrorLogger = (error, request, response) => {
109
+ const log = (0, internal_logger_1.internalLogger)("http");
110
+ const route = `${request.method} ${request.url}`;
111
+ if (response.statusCode < 500) {
112
+ log.warn({ statusCode: response.statusCode, route }, `HTTP ${response.statusCode} ${route} — ${error?.message ?? error}`);
113
+ return;
114
+ }
115
+ log.error({ err: error, statusCode: response.statusCode, route }, `HTTP ${response.statusCode} ${route} — ${error?.name ?? "Error"}: ${error?.message ?? error}`);
116
+ };
117
+ exports.defaultErrorLogger = defaultErrorLogger;
118
+ /**
119
+ * Megh's request error handler: runs the exception filters in order, then
120
+ * falls back to {@link defaultErrorResponse}.
121
+ *
122
+ * Order: `@UseFilters` on the route, on the controller, then the global
123
+ * filters in registration order.
124
+ */
125
+ class MeghErrorHandler {
126
+ globalFilters = [];
127
+ isDevelopment;
128
+ logger;
129
+ constructor(options = {}) {
130
+ this.isDevelopment =
131
+ options.isDevelopment ?? (() => process.env.NODE_ENV === "development");
132
+ this.logger = options.logger ?? exports.defaultErrorLogger;
133
+ }
134
+ /** Append global filters. */
135
+ addFilters(filters) {
136
+ for (const f of filters)
137
+ this.globalFilters.push(resolveFilter(f));
138
+ return this;
139
+ }
140
+ setLogger(logger) {
141
+ this.logger = logger;
142
+ return this;
143
+ }
144
+ /** Install on a Fastify instance as its error and not-found handler. */
145
+ install(app) {
146
+ app.setErrorHandler((error, request, reply) => this.handle(error, request, reply));
147
+ try {
148
+ app.setNotFoundHandler(async (request) => {
149
+ throw new http_exceptions_1.NotFoundException(`Route ${request.method} ${request.url.split("?")[0]} not found`);
150
+ });
151
+ }
152
+ catch {
153
+ // The app already set its own not-found handler; keep it.
154
+ }
155
+ }
156
+ async handle(error, request, reply) {
157
+ const isDevelopment = this.isDevelopment();
158
+ const routeFilters = request.routeOptions?.config?.[exports.ROUTE_FILTERS_CONFIG_KEY] ?? [];
159
+ let current = error;
160
+ for (const filter of [...routeFilters, ...this.globalFilters]) {
161
+ if (!accepts(filter, current))
162
+ continue;
163
+ const response = defaultErrorResponse(current, isDevelopment);
164
+ reply.code(response.statusCode);
165
+ let result;
166
+ try {
167
+ result = await filter.run(current, {
168
+ request,
169
+ reply,
170
+ isDevelopment,
171
+ response,
172
+ });
173
+ }
174
+ catch (filterError) {
175
+ (0, internal_logger_1.internalLogger)("http").error({ err: filterError }, "Exception filter threw; answering with the default error response");
176
+ break;
177
+ }
178
+ if (reply.sent)
179
+ return reply;
180
+ if (result instanceof Error) {
181
+ current = result;
182
+ continue;
183
+ }
184
+ if (result !== undefined)
185
+ return reply.send(result);
186
+ }
187
+ const response = defaultErrorResponse(current, isDevelopment);
188
+ if (this.logger) {
189
+ try {
190
+ this.logger(current, request, response);
191
+ }
192
+ catch {
193
+ // A broken logger must not break the response.
194
+ }
195
+ }
196
+ if (response.headers)
197
+ reply.headers(response.headers);
198
+ return reply
199
+ .code(response.statusCode)
200
+ .type("application/json; charset=utf-8")
201
+ .serializer((payload) => JSON.stringify(payload))
202
+ .send(response.body);
203
+ }
204
+ }
205
+ exports.MeghErrorHandler = MeghErrorHandler;
206
+ //# sourceMappingURL=error-handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-handler.js","sourceRoot":"","sources":["../../src/errors/error-handler.ts"],"names":[],"mappings":";;;AAmDA,oDA0DC;AAGD,sCAoBC;A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,CAAC;gBACrB,IAAA,gCAAc,EAAC,MAAM,CAAC,CAAC,KAAK,CAC1B,EAAE,GAAG,EAAE,WAAW,EAAE,EACpB,mEAAmE,CACpE,CAAC;gBACF,MAAM;YACR,CAAC;YAED,IAAI,KAAK,CAAC,IAAI;gBAAE,OAAO,KAAK,CAAC;YAC7B,IAAI,MAAM,YAAY,KAAK,EAAE,CAAC;gBAC5B,OAAO,GAAG,MAAM,CAAC;gBACjB,SAAS;YACX,CAAC;YACD,IAAI,MAAM,KAAK,SAAS;gBAAE,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACtD,CAAC;QAED,MAAM,QAAQ,GAAG,oBAAoB,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;QAC9D,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC;gBACH,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;YAC1C,CAAC;YAAC,MAAM,CAAC;gBACP,+CAA+C;YACjD,CAAC;QACH,CAAC;QACD,IAAI,QAAQ,CAAC,OAAO;YAAE,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QACtD,OAAO,KAAK;aACT,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;aACzB,IAAI,CAAC,iCAAiC,CAAC;aACvC,UAAU,CAAC,CAAC,OAAgB,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;aACzD,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACzB,CAAC;CACF;AAxFD,4CAwFC"}
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+ import "reflect-metadata";
8
+ import type { FastifyReply, FastifyRequest } from "fastify";
9
+ /** The status, headers and body Megh sends for an error. */
10
+ export interface ErrorResponse {
11
+ statusCode: number;
12
+ headers?: Record<string, string | number | string[]>;
13
+ body: ErrorResponseBody;
14
+ }
15
+ /** The default JSON error body. */
16
+ export interface ErrorResponseBody {
17
+ code: number;
18
+ status: "Error";
19
+ message: string;
20
+ /** The exception's payload. Sent for 4xx, and for 5xx in development only. */
21
+ data?: unknown;
22
+ /** Individual validation issues. */
23
+ errors?: unknown;
24
+ /** Error class name. Development only. */
25
+ error?: string;
26
+ /** First stack frames. Development only. */
27
+ stack?: string[];
28
+ [key: string]: unknown;
29
+ }
30
+ /** What a filter gets besides the error. */
31
+ export interface ErrorContext {
32
+ request: FastifyRequest;
33
+ reply: FastifyReply;
34
+ /** True when `NODE_ENV` is `"development"`. */
35
+ isDevelopment: boolean;
36
+ /**
37
+ * What Megh sends if no filter handles the error. Build on it to keep the
38
+ * status and the production redaction, or ignore it.
39
+ */
40
+ response: ErrorResponse;
41
+ }
42
+ /**
43
+ * Handles errors thrown while serving a request.
44
+ *
45
+ * What `catch` does decides what happens next:
46
+ *
47
+ * - Return a value: it becomes the response body. The status is
48
+ * `ctx.response.statusCode` unless the filter calls `ctx.reply.code()`.
49
+ * - Return an `Error` (an `HttpException`, say): the error is replaced and
50
+ * handling continues with the next filter, then the default response. Use
51
+ * this to map domain errors to HTTP ones.
52
+ * - Send the reply itself (`ctx.reply.send(...)`): nothing else runs.
53
+ * - Return `undefined` without sending: the next filter runs. Use this for
54
+ * filters that only report errors.
55
+ *
56
+ * A filter class is resolved through the DI container, so its constructor
57
+ * can take services. Limit it to some error types with {@link Catch}.
58
+ */
59
+ export interface ExceptionFilter<E = any> {
60
+ catch(error: E, ctx: ErrorContext): unknown | Promise<unknown>;
61
+ }
62
+ /** A function filter, with the same contract as {@link ExceptionFilter.catch}. */
63
+ export type ErrorHandlerFunction<E = any> = (error: E, ctx: ErrorContext) => unknown | Promise<unknown>;
64
+ /** Anything accepted where a filter is expected. */
65
+ export type ExceptionFilterLike = (new (...args: any[]) => ExceptionFilter) | ExceptionFilter | ErrorHandlerFunction;
66
+ type ErrorClass = abstract new (...args: any[]) => unknown;
67
+ export declare const CATCH_META_KEY = "megh:exception-filter:catch";
68
+ export declare const FILTERS_META_KEY = "megh:exception-filter:filters";
69
+ /**
70
+ * Restrict an exception filter to errors of the given classes (subclasses
71
+ * included). Without `@Catch`, or with `@Catch()`, the filter sees every
72
+ * error.
73
+ *
74
+ * @Catch(EntityNotFoundError)
75
+ * class EntityNotFoundFilter implements ExceptionFilter<EntityNotFoundError> {
76
+ * catch(error: EntityNotFoundError) {
77
+ * return new NotFoundException(error.message);
78
+ * }
79
+ * }
80
+ *
81
+ * The class is also registered with the DI container.
82
+ */
83
+ export declare function Catch(...types: ErrorClass[]): ClassDecorator;
84
+ /**
85
+ * Apply exception filters to every route of a controller, or to one route.
86
+ * They run before the global filters: route filters first, then controller
87
+ * filters.
88
+ *
89
+ * @UseFilters(PaymentErrorFilter)
90
+ * @ApiController("/payments")
91
+ * class PaymentsController {}
92
+ */
93
+ export declare function UseFilters(...filters: ExceptionFilterLike[]): ClassDecorator & MethodDecorator;
94
+ /** Filters declared with {@link UseFilters}: route ones first, then the controller's. */
95
+ export declare function getDeclaredFilters(controller: Function, method: string): ExceptionFilterLike[];
96
+ export {};
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FILTERS_META_KEY = exports.CATCH_META_KEY = void 0;
4
+ exports.Catch = Catch;
5
+ exports.UseFilters = UseFilters;
6
+ exports.getDeclaredFilters = getDeclaredFilters;
7
+ /**
8
+ * @copyright 2024
9
+ * @author Tareq Hossain
10
+ * @email xtrinsic96@gmail.com
11
+ * @url https://github.com/xtareq
12
+ */
13
+ require("reflect-metadata");
14
+ const di_1 = require("../di");
15
+ exports.CATCH_META_KEY = "megh:exception-filter:catch";
16
+ exports.FILTERS_META_KEY = "megh:exception-filter:filters";
17
+ /**
18
+ * Restrict an exception filter to errors of the given classes (subclasses
19
+ * included). Without `@Catch`, or with `@Catch()`, the filter sees every
20
+ * error.
21
+ *
22
+ * @Catch(EntityNotFoundError)
23
+ * class EntityNotFoundFilter implements ExceptionFilter<EntityNotFoundError> {
24
+ * catch(error: EntityNotFoundError) {
25
+ * return new NotFoundException(error.message);
26
+ * }
27
+ * }
28
+ *
29
+ * The class is also registered with the DI container.
30
+ */
31
+ function Catch(...types) {
32
+ return (target) => {
33
+ Reflect.defineMetadata(exports.CATCH_META_KEY, types, target);
34
+ (0, di_1.Injectable)()(target);
35
+ };
36
+ }
37
+ /**
38
+ * Apply exception filters to every route of a controller, or to one route.
39
+ * They run before the global filters: route filters first, then controller
40
+ * filters.
41
+ *
42
+ * @UseFilters(PaymentErrorFilter)
43
+ * @ApiController("/payments")
44
+ * class PaymentsController {}
45
+ */
46
+ function UseFilters(...filters) {
47
+ return (target, propertyKey) => {
48
+ const existing = (propertyKey === undefined
49
+ ? Reflect.getMetadata(exports.FILTERS_META_KEY, target)
50
+ : Reflect.getMetadata(exports.FILTERS_META_KEY, target, propertyKey)) ?? [];
51
+ const next = [...existing, ...filters];
52
+ if (propertyKey === undefined) {
53
+ Reflect.defineMetadata(exports.FILTERS_META_KEY, next, target);
54
+ }
55
+ else {
56
+ Reflect.defineMetadata(exports.FILTERS_META_KEY, next, target, propertyKey);
57
+ }
58
+ };
59
+ }
60
+ /** Filters declared with {@link UseFilters}: route ones first, then the controller's. */
61
+ function getDeclaredFilters(controller, method) {
62
+ return [
63
+ ...(Reflect.getMetadata(exports.FILTERS_META_KEY, controller.prototype, method) ??
64
+ []),
65
+ ...(Reflect.getMetadata(exports.FILTERS_META_KEY, controller) ?? []),
66
+ ];
67
+ }
68
+ //# sourceMappingURL=exception-filter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exception-filter.js","sourceRoot":"","sources":["../../src/errors/exception-filter.ts"],"names":[],"mappings":";;;AAkGA,sBAKC;AAWD,gCAeC;AAGD,gDASC;AA7ID;;;;;GAKG;AACH,4BAA0B;AAE1B,8B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