quantum-flow 1.0.6 → 1.1.1

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 (46) hide show
  1. package/README.md +37 -48
  2. package/dist/app/aws/decorators.d.ts +8 -0
  3. package/dist/app/aws/decorators.js +14 -0
  4. package/dist/app/aws/index.d.ts +1 -0
  5. package/dist/app/aws/index.js +1 -0
  6. package/dist/app/aws/lambda.d.ts +2 -2
  7. package/dist/app/aws/lambda.js +4 -1
  8. package/dist/app/http/Application.d.ts +0 -1
  9. package/dist/app/http/Application.js +28 -32
  10. package/dist/app/http/decorators.d.ts +2 -5
  11. package/dist/app/http/decorators.js +2 -40
  12. package/dist/constants.d.ts +9 -3
  13. package/dist/constants.js +16 -4
  14. package/dist/core/Controller.d.ts +17 -29
  15. package/dist/core/Controller.js +139 -83
  16. package/dist/core/Endpoint.d.ts +19 -10
  17. package/dist/core/Endpoint.js +41 -11
  18. package/dist/core/index.d.ts +1 -1
  19. package/dist/core/utils/extractors.d.ts +0 -7
  20. package/dist/core/utils/extractors.js +9 -18
  21. package/dist/core/utils/index.d.ts +1 -0
  22. package/dist/core/utils/index.js +1 -0
  23. package/dist/core/utils/middlewares.d.ts +3 -0
  24. package/dist/core/utils/middlewares.js +22 -0
  25. package/dist/examples/controllers/socket.d.ts +0 -16
  26. package/dist/examples/controllers/socket.js +5 -46
  27. package/dist/examples/controllers/user.d.ts +13 -1
  28. package/dist/examples/controllers/user.js +27 -13
  29. package/dist/examples/controllers/userMetadata.d.ts +3 -0
  30. package/dist/examples/controllers/userMetadata.js +32 -0
  31. package/dist/examples/server.js +6 -22
  32. package/dist/types/common.d.ts +31 -7
  33. package/dist/types/common.js +12 -0
  34. package/dist/types/controller.d.ts +33 -0
  35. package/dist/types/http.d.ts +5 -9
  36. package/dist/types/lambda.d.ts +8 -1
  37. package/dist/utils/controller.d.ts +4 -9
  38. package/dist/utils/controller.js +8 -7
  39. package/dist/utils/endpoint.d.ts +2 -0
  40. package/dist/utils/endpoint.js +13 -0
  41. package/dist/utils/helper.d.ts +5 -1
  42. package/dist/utils/helper.js +54 -17
  43. package/dist/utils/index.d.ts +1 -0
  44. package/dist/utils/index.js +1 -0
  45. package/dist/utils/server.js +4 -0
  46. package/package.json +1 -1
package/README.md CHANGED
@@ -16,6 +16,16 @@ yarn build
16
16
 
17
17
  # Usage
18
18
 
19
+ You can use controllers and server functionality by importing controllers and creating server instances as shown in the examples above. Use your preferred testing framework to write unit and integration tests.
20
+
21
+ # Project Structure
22
+
23
+ - `quantum-flow/http` - Main application source code for HTTP servers.
24
+ - `quantum-flow/aws` - Main application source code AWS Lambda.
25
+ - `quantum-flow/core` - Core framework components like Controller and Endpoint.
26
+
27
+ ---
28
+
19
29
  ## Defining Controllers
20
30
 
21
31
  Use the `@Controller` decorator to define controllers with options such as prefix, sub-controllers, middlewares, and interceptors.
@@ -23,29 +33,30 @@ Use the `@Controller` decorator to define controllers with options such as prefi
23
33
  ```typescript
24
34
  import { Controller } from 'quantum-flow/core';
25
35
 
36
+ @Controller(api, [...middlewares])
26
37
  @Controller({
27
38
  prefix: 'api',
28
39
  controllers: [UserController, SocketController],
29
- interceptors: [(resp) => resp],
40
+ middelwares: [...middlewares],
41
+ interceptor: (parsedRequest, httpRequest, httpResponse) => parsedRequest,
30
42
  })
43
+ @Catch((error) => ({ status: 400, error }))
31
44
  class RootController {}
32
45
  ```
33
46
 
34
- ## Creating a Server
47
+ ## Creating a http Server
35
48
 
36
49
  Use the `@Server` decorator with configuration options like port, host, controllers, and WebSocket enablement.
37
50
 
38
51
  ```typescript
39
- import { Server, Port, Host, Use, Intercept, Catch, HttpServer } from 'quantum-flow/http';
52
+ import { Server, Port, Host, Use, Catch, HttpServer } from 'quantum-flow/http';
40
53
 
41
- @Server({
42
- controllers: [RootController],
43
- })
54
+ @Server({ controllers: [RootController] })
44
55
  @Port(3000)
45
56
  @Host('localhost')
46
- @Use((res: any) => res)
47
- @Intercept((data, req, res) => data)
48
- @Catch((error) => error)
57
+ @Use((data) => data)
58
+ @Use((data) => data)
59
+ @Catch((error) => ({ status: 400, error }))
49
60
  class App {}
50
61
 
51
62
  const server = new HttpServer(App);
@@ -56,7 +67,6 @@ server.listen().catch(console.error);
56
67
  ## Middlewares, Interceptors, and Error Handlers
57
68
 
58
69
  - Use `@Use` to apply middlewares.
59
- - Use `@Intercept` to apply interceptors.
60
70
  - Use `@Catch` to handle errors.
61
71
  - Use `@Port` and `@Host` to configure server port and host.
62
72
 
@@ -67,8 +77,9 @@ server.listen().catch(console.error);
67
77
  - Use `@Query` to handle query parameters.
68
78
  - Use `@Params` to access route parameters.
69
79
  - Use `@Multipart` for handling multipart/form-data requests.
70
- - Use `@Request` to access the entire request object.
71
- - Use `@Response` to access the response object.
80
+ - Use `@Request` to access the original request object.
81
+ - Use `@Response` to access the original object.
82
+ - Use `@InjectWS` to access the WebsocketService.
72
83
 
73
84
  # AWS Lambda Support
74
85
 
@@ -77,6 +88,20 @@ Use `LambdaAdapter` to convert API Gateway events to requests and responses. Cre
77
88
  ```typescript
78
89
  Example Lambda handler creation
79
90
  import { LambdaAdapter } from 'quantum-flow/aws';
91
+
92
+ let dbConnection = null;
93
+
94
+ @Controller({
95
+ prefix: 'api',
96
+ controllers: [UserController, SocketController],
97
+ })
98
+ class RootController {
99
+ async beforeStart(){
100
+ if(!dbConnection){
101
+ connection = await connect()
102
+ }
103
+ }
104
+ }
80
105
  export const handler = LambdaAdapter.createHandler(RootController);
81
106
  ```
82
107
 
@@ -163,37 +188,10 @@ export class Socket {
163
188
  );
164
189
  }
165
190
  }
166
- @Server({
167
- controllers: [Socket],
168
- websocket: { enabled: true },
169
- })
170
- @Use(middleware)
171
- class App {}
172
191
  ```
173
192
 
174
- # Usage
175
-
176
- You can use controllers and server functionality by importing controllers and creating server instances as shown in the examples above. Use your preferred testing framework to write unit and integration tests.
177
-
178
- # Project Structure
179
-
180
- - `quantum-flow/http` - Main application source code for HTTP servers.
181
- - `quantum-flow/aws` - Main application source code AWS Lambda.
182
- - `quantum-flow/core` - Core framework components like Controller and Endpoint.
183
-
184
- ---
185
-
186
193
  # Decorators
187
194
 
188
- ### Server
189
-
190
- Class decorator to configure the server with options like controllers, global middlewares, and interceptors.
191
-
192
- ```typescript
193
- @Server({ controllers: [RootController] })
194
- class App {}
195
- ```
196
-
197
195
  ### Use
198
196
 
199
197
  Class decorator to add global middlewares to the server.
@@ -203,15 +201,6 @@ Class decorator to add global middlewares to the server.
203
201
  class App {}
204
202
  ```
205
203
 
206
- ### Intercept
207
-
208
- Class decorator to add global interceptors to the server.
209
-
210
- ```typescript
211
- @Intercept(interceptor)
212
- class App {}
213
- ```
214
-
215
204
  ### Catch
216
205
 
217
206
  Class decorator to set a global error handler for the server.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Parameter decorator to inject AWS lambda event.
3
+ */
4
+ export declare const LambdaEvent: () => (target: any, propertyKey: string | symbol, parameterIndex: number) => void;
5
+ /**
6
+ * Parameter decorator to inject AWS lambda context.
7
+ */
8
+ export declare const LambdaContext: () => (target: any, propertyKey: string | symbol, parameterIndex: number) => void;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LambdaContext = exports.LambdaEvent = void 0;
4
+ const _utils_1 = require("../../utils/index.js");
5
+ /**
6
+ * Parameter decorator to inject AWS lambda event.
7
+ */
8
+ const LambdaEvent = () => (0, _utils_1.createParamDecorator)('event');
9
+ exports.LambdaEvent = LambdaEvent;
10
+ /**
11
+ * Parameter decorator to inject AWS lambda context.
12
+ */
13
+ const LambdaContext = () => (0, _utils_1.createParamDecorator)('context');
14
+ exports.LambdaContext = LambdaContext;
@@ -1 +1,2 @@
1
1
  export * from './lambda';
2
+ export * from './decorators';
@@ -15,3 +15,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./lambda"), exports);
18
+ __exportStar(require("./decorators"), exports);
@@ -1,11 +1,11 @@
1
1
  import { APIGatewayProxyEvent, APIGatewayProxyResult, Context, Handler } from 'aws-lambda';
2
- import { LambdaRequest, LambdaResponse } from '../../types/index.js';
2
+ import { LambdaRequest, LambdaResponse, LambdaApp } from '../../types/index.js';
3
3
  export declare class LambdaAdapter {
4
4
  private static getHeaderValue;
5
5
  static toRequest(event: APIGatewayProxyEvent, context: Context): LambdaRequest;
6
6
  static createResponseBody(response: any): any;
7
7
  static toLambdaResponse(response: any, request?: LambdaRequest): LambdaResponse;
8
- static createHandler(Contoller: any): Handler<APIGatewayProxyEvent, APIGatewayProxyResult>;
8
+ static createHandler(Contoller: new (...args: any[]) => LambdaApp): Handler<APIGatewayProxyEvent, APIGatewayProxyResult>;
9
9
  private static safeHeaders;
10
10
  private static safeParams;
11
11
  private static getSourceIp;
@@ -63,7 +63,7 @@ class LambdaAdapter {
63
63
  body,
64
64
  params: this.safeParams(event.pathParameters),
65
65
  cookies,
66
- raw: event,
66
+ event,
67
67
  context,
68
68
  isBase64Encoded: event.isBase64Encoded || false,
69
69
  requestId: context.awsRequestId,
@@ -156,6 +156,9 @@ class LambdaAdapter {
156
156
  static createHandler(Contoller) {
157
157
  const handler = async (event, context) => {
158
158
  const instance = new Contoller();
159
+ if (Object.hasOwn(instance, 'beforeStart')) {
160
+ await instance.beforeStart?.();
161
+ }
159
162
  try {
160
163
  const request = LambdaAdapter.toRequest(event, context);
161
164
  if (typeof instance.handleRequest === 'function') {
@@ -17,7 +17,6 @@ export declare class HttpServer extends Socket {
17
17
  private createRequest;
18
18
  private applyMiddlewares;
19
19
  private findController;
20
- private applyInterceptors;
21
20
  private sendResponse;
22
21
  private handleError;
23
22
  }
@@ -35,9 +35,11 @@ class HttpServer extends Socket_1.Socket {
35
35
  ║ 📍 Host: ${this.config.host}
36
36
  ║ 🔌 Port: ${this.config.port}
37
37
  ║ 🔌 Websocket: ${!!this.config.websocket}
38
- ║ 🔧 Middlewares: ${this.config.globalMiddlewares?.length || 0}
39
- 🎯 Interceptors: ${this.config.globalInterceptors?.length || 0}
40
- 📦 Controllers: ${this.config.controllers?.length || 0}
38
+ ║ 🔧 Global Middlewares: ${this.config.middlewares?.length || 0}
39
+ 🔧 Error middlewares: ${this.config.errorHandler?.length || 0}
40
+ 🎯 Global Interceptors: ${!!this.config.interceptor?.length}
41
+ ║ 📦 Controllers: ${_constants_1.STATISTIC.controllers}
42
+ ║ 📦 Routes: ${_constants_1.STATISTIC.routes}
41
43
  ╚════════════════════════════════════════╝
42
44
  `);
43
45
  }
@@ -99,10 +101,12 @@ class HttpServer extends Socket_1.Socket {
99
101
  const startTime = Date.now();
100
102
  try {
101
103
  const request = await this.createRequest(req);
102
- let processedRequest = await this.applyMiddlewares(request, res);
103
- const data = await this.findController(processedRequest, res);
104
- const finalResponse = await this.applyInterceptors(data, request, res);
105
- await this.sendResponse(res, finalResponse, startTime);
104
+ let appRequest = await this.applyMiddlewares(request, req, res);
105
+ let data = await this.findController(appRequest, req, res);
106
+ if (this.config.interceptor) {
107
+ data = await this.config.interceptor(data, req, res);
108
+ }
109
+ await this.sendResponse(res, data, startTime);
106
110
  }
107
111
  catch (error) {
108
112
  await this.handleError(error, req, res, startTime);
@@ -121,9 +125,8 @@ class HttpServer extends Socket_1.Socket {
121
125
  const fullUrl = `${protocol}://${host}${req.url}`;
122
126
  const whatwgUrl = new URL(fullUrl);
123
127
  return {
124
- method: req.method,
128
+ method: req.method?.toUpperCase(),
125
129
  url: whatwgUrl,
126
- path: whatwgUrl.pathname,
127
130
  headers: req.headers,
128
131
  body: parsedBody,
129
132
  rawBody: rawBody,
@@ -134,21 +137,21 @@ class HttpServer extends Socket_1.Socket {
134
137
  _startTime: Date.now(),
135
138
  };
136
139
  }
137
- async applyMiddlewares(request, res) {
138
- let processed = request;
139
- for (const middleware of this.config.globalMiddlewares || []) {
140
- const result = await middleware(processed, res);
140
+ async applyMiddlewares(appRequest, request, response) {
141
+ let processed = appRequest;
142
+ for (const middleware of this.config.middlewares?.reverse() || []) {
143
+ const result = await middleware(processed, request, response);
141
144
  if (result) {
142
- processed = { ...processed, ...result };
145
+ processed = result;
143
146
  }
144
147
  }
145
148
  return processed;
146
149
  }
147
- async findController(request, response) {
150
+ async findController(appRequest, request, response) {
148
151
  for (const ControllerClass of this.config.controllers || []) {
149
152
  const instance = new ControllerClass();
150
153
  if (typeof instance.handleRequest === 'function') {
151
- const data = await instance.handleRequest(request, response);
154
+ const data = await instance.handleRequest(appRequest, request, response);
152
155
  if (data && data.status !== 404) {
153
156
  return data;
154
157
  }
@@ -156,18 +159,11 @@ class HttpServer extends Socket_1.Socket {
156
159
  }
157
160
  return {
158
161
  status: 404,
159
- data: { message: `Route ${request.method} ${request.path} not found` },
162
+ data: { message: `Route ${appRequest.method} ${appRequest.url.pathname} not found` },
160
163
  };
161
164
  }
162
- async applyInterceptors(data, request, response) {
163
- let processed = data;
164
- for (const interceptor of this.config.globalInterceptors || []) {
165
- processed = await interceptor(processed, request, response);
166
- }
167
- return processed;
168
- }
169
165
  async sendResponse(res, data, startTime) {
170
- const resp = data?.data !== undefined ? data.data : data;
166
+ const response = data?.data !== undefined ? data.data : data;
171
167
  if (!res.headersSent) {
172
168
  if (!res.getHeader('Content-Type')) {
173
169
  res.setHeader('Content-Type', 'application/json');
@@ -182,9 +178,9 @@ class HttpServer extends Socket_1.Socket {
182
178
  }
183
179
  res.setHeader('X-Response-Time', `${Date.now() - startTime}ms`);
184
180
  res.statusCode = data.status ?? 200;
185
- res.end(JSON.stringify(resp));
181
+ res.end(JSON.stringify(response));
186
182
  }
187
- async handleError(error, req, res, startTime) {
183
+ async handleError(error, request, response, startTime) {
188
184
  let errorResponse = {
189
185
  status: error.status || 500,
190
186
  data: {
@@ -192,17 +188,17 @@ class HttpServer extends Socket_1.Socket {
192
188
  errors: error.errors || [],
193
189
  },
194
190
  };
195
- if (!this.config.globalErrorHandler) {
196
- return this.sendResponse(res, errorResponse, startTime);
191
+ if (!this.config.errorHandler) {
192
+ return this.sendResponse(response, errorResponse, startTime);
197
193
  }
198
194
  try {
199
- const intercepted = await this.config.globalErrorHandler(error, req, res);
200
- errorResponse = { ...errorResponse, ...intercepted };
195
+ const intercepted = await this.config.errorHandler(error, request, response);
196
+ errorResponse = intercepted;
201
197
  }
202
198
  catch (cathed) {
203
199
  Object.assign(errorResponse, cathed);
204
200
  }
205
- return this.sendResponse(res, errorResponse, startTime);
201
+ return this.sendResponse(response, errorResponse, startTime);
206
202
  }
207
203
  }
208
204
  exports.HttpServer = HttpServer;
@@ -1,7 +1,4 @@
1
- import { Conf, Interceptor } from '../../types/index.js';
2
- export declare function Server(config?: Conf): (target: any) => any;
3
- export declare function Use(middleware: any): (target: any) => any;
4
- export declare function Intercept(interceptor: Interceptor): (target: any) => any;
5
- export declare function Catch(handler: any): (target: any) => any;
1
+ import { ServerConfig } from '../../types/index.js';
2
+ export declare function Server(config?: ServerConfig): (target: any) => any;
6
3
  export declare function Port(port: number): (target: any) => any;
7
4
  export declare function Host(host: string): (target: any) => any;
@@ -1,9 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Server = Server;
4
- exports.Use = Use;
5
- exports.Intercept = Intercept;
6
- exports.Catch = Catch;
7
4
  exports.Port = Port;
8
5
  exports.Host = Host;
9
6
  const _constants_1 = require("../../constants.js");
@@ -14,8 +11,8 @@ function Server(config = {}) {
14
11
  ...existingConfig,
15
12
  ...config,
16
13
  controllers: [...(existingConfig.controllers || []), ...(config.controllers || [])],
17
- globalMiddlewares: existingConfig.globalMiddlewares || config.globalMiddlewares,
18
- globalInterceptors: existingConfig.globalInterceptors || config.globalInterceptors || [],
14
+ middlewares: [...(existingConfig.middlewares ?? []), ...(config.middlewares ?? [])],
15
+ interceptors: existingConfig.interceptor ?? config.interceptor,
19
16
  };
20
17
  Reflect.defineMetadata(_constants_1.SERVER_CONFIG_KEY, mergedConfig, target);
21
18
  if (config.controllers) {
@@ -24,41 +21,6 @@ function Server(config = {}) {
24
21
  return target;
25
22
  };
26
23
  }
27
- function Use(middleware) {
28
- return function (target) {
29
- const existingConfig = Reflect.getMetadata(_constants_1.SERVER_CONFIG_KEY, target) || {};
30
- const middlewares = existingConfig.globalMiddlewares || [];
31
- middlewares.push(middleware);
32
- console.log(middlewares);
33
- Reflect.defineMetadata(_constants_1.SERVER_CONFIG_KEY, {
34
- ...existingConfig,
35
- globalMiddlewares: middlewares,
36
- }, target);
37
- return target;
38
- };
39
- }
40
- function Intercept(interceptor) {
41
- return function (target) {
42
- const existingConfig = Reflect.getMetadata(_constants_1.SERVER_CONFIG_KEY, target) || {};
43
- const interceptors = existingConfig.globalInterceptors || [];
44
- interceptors.push(interceptor);
45
- Reflect.defineMetadata(_constants_1.SERVER_CONFIG_KEY, {
46
- ...existingConfig,
47
- globalInterceptors: interceptors,
48
- }, target);
49
- return target;
50
- };
51
- }
52
- function Catch(handler) {
53
- return function (target) {
54
- const existingConfig = Reflect.getMetadata(_constants_1.SERVER_CONFIG_KEY, target) || {};
55
- Reflect.defineMetadata(_constants_1.SERVER_CONFIG_KEY, {
56
- ...existingConfig,
57
- globalErrorHandler: handler,
58
- }, target);
59
- return target;
60
- };
61
- }
62
24
  function Port(port) {
63
25
  return function (target) {
64
26
  const existingConfig = Reflect.getMetadata(_constants_1.SERVER_CONFIG_KEY, target) || {};
@@ -1,16 +1,22 @@
1
1
  export declare const PARAM_METADATA_KEY = "design:parameters";
2
2
  export declare const APP_METADATA_KEY = "app:configuration";
3
- export declare const ROUTE_PREFIX = "route:profix";
4
- export declare const MIDDLEWARES = "route:middlewares";
3
+ export declare const ROUTE_PREFIX = "route:prefix";
4
+ export declare const ROUTE_MIDDLEWARES = "route:middlewares";
5
+ export declare const MIDDLEWARES = "controller:middlewares";
5
6
  export declare const CONTROLLERS = "app:controllers";
6
- export declare const INTERCEPTORS = "app:interceptors";
7
+ export declare const INTERCEPTOR = "app:interceptors";
7
8
  export declare const ENDPOINT = "route:endpoints";
8
9
  export declare const OK_METADATA_KEY = "custom:ok";
9
10
  export declare const SERVER_CONFIG_KEY = "server:config";
10
11
  export declare const SERVER_MODULES_KEY = "server:modules";
12
+ export declare const USE_MIDDLEWARE = "controller:usemiddleware";
11
13
  export declare const WS_METADATA_KEY = "websocket:handler";
12
14
  export declare const WS_TOPIC_KEY = "websocket:topic";
13
15
  export declare const WS_SERVICE_KEY = "websocket:service";
16
+ export declare const INTECEPT = "server:intercept";
17
+ export declare const CATCH = "server:catch";
14
18
  export declare const STOPPED = "\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n\u2551 \uD83D\uDC4B Server stopped \u2551\n\u2551 \uD83D\uDCCA Status: STOPPED \u2551\n\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\n ";
15
19
  export declare const OK_STATUSES: number[];
16
20
  export declare const TO_VALIDATE: string[];
21
+ export declare const STATISTIC: Record<'controllers' | 'routes', number>;
22
+ export declare const INCREMENT_STATISTIC: (prop: "controllers" | "routes") => void;
package/dist/constants.js CHANGED
@@ -1,19 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TO_VALIDATE = exports.OK_STATUSES = exports.STOPPED = exports.WS_SERVICE_KEY = exports.WS_TOPIC_KEY = exports.WS_METADATA_KEY = exports.SERVER_MODULES_KEY = exports.SERVER_CONFIG_KEY = exports.OK_METADATA_KEY = exports.ENDPOINT = exports.INTERCEPTORS = exports.CONTROLLERS = exports.MIDDLEWARES = exports.ROUTE_PREFIX = exports.APP_METADATA_KEY = exports.PARAM_METADATA_KEY = void 0;
3
+ exports.INCREMENT_STATISTIC = exports.STATISTIC = exports.TO_VALIDATE = exports.OK_STATUSES = exports.STOPPED = exports.CATCH = exports.INTECEPT = exports.WS_SERVICE_KEY = exports.WS_TOPIC_KEY = exports.WS_METADATA_KEY = exports.USE_MIDDLEWARE = exports.SERVER_MODULES_KEY = exports.SERVER_CONFIG_KEY = exports.OK_METADATA_KEY = exports.ENDPOINT = exports.INTERCEPTOR = exports.CONTROLLERS = exports.MIDDLEWARES = exports.ROUTE_MIDDLEWARES = exports.ROUTE_PREFIX = exports.APP_METADATA_KEY = exports.PARAM_METADATA_KEY = void 0;
4
4
  exports.PARAM_METADATA_KEY = 'design:parameters';
5
5
  exports.APP_METADATA_KEY = 'app:configuration';
6
- exports.ROUTE_PREFIX = 'route:profix';
7
- exports.MIDDLEWARES = 'route:middlewares';
6
+ exports.ROUTE_PREFIX = 'route:prefix';
7
+ exports.ROUTE_MIDDLEWARES = 'route:middlewares';
8
+ exports.MIDDLEWARES = 'controller:middlewares';
8
9
  exports.CONTROLLERS = 'app:controllers';
9
- exports.INTERCEPTORS = 'app:interceptors';
10
+ exports.INTERCEPTOR = 'app:interceptors';
10
11
  exports.ENDPOINT = 'route:endpoints';
11
12
  exports.OK_METADATA_KEY = 'custom:ok';
12
13
  exports.SERVER_CONFIG_KEY = 'server:config';
13
14
  exports.SERVER_MODULES_KEY = 'server:modules';
15
+ exports.USE_MIDDLEWARE = 'controller:usemiddleware';
14
16
  exports.WS_METADATA_KEY = 'websocket:handler';
15
17
  exports.WS_TOPIC_KEY = 'websocket:topic';
16
18
  exports.WS_SERVICE_KEY = 'websocket:service';
19
+ exports.INTECEPT = 'server:intercept';
20
+ exports.CATCH = 'server:catch';
17
21
  exports.STOPPED = `
18
22
  ╔════════════════════════════════════════╗
19
23
  ║ 👋 Server stopped ║
@@ -22,3 +26,11 @@ exports.STOPPED = `
22
26
  `;
23
27
  exports.OK_STATUSES = [200, 201, 202, 203, 204, 205, 206, 207, 208, 226];
24
28
  exports.TO_VALIDATE = ['headers', 'params', 'multipart', 'query', 'body'];
29
+ exports.STATISTIC = {
30
+ controllers: 0,
31
+ routes: 0,
32
+ };
33
+ const INCREMENT_STATISTIC = (prop) => {
34
+ exports.STATISTIC[prop] = exports.STATISTIC[prop] + 1;
35
+ };
36
+ exports.INCREMENT_STATISTIC = INCREMENT_STATISTIC;
@@ -1,16 +1,6 @@
1
- import { Interceptor, Middleware } from '../types/index.js';
2
- import { ServerResponse } from 'http';
1
+ import { AppRequest, ControllerClass, ControllerConfig, ControllerInstance, InterceptorCB, RouteContext } from '../types/index.js';
2
+ import { IncomingMessage, ServerResponse } from 'http';
3
3
  import 'reflect-metadata';
4
- type ControllerClass = {
5
- new (...args: any[]): any;
6
- };
7
- type ControllerInstance = InstanceType<ControllerClass>;
8
- interface ControllerConfig {
9
- prefix: string;
10
- middlewares?: Array<Middleware>;
11
- controllers?: ControllerClass[];
12
- interceptors?: Array<(...args: any[]) => any> | ((...args: any[]) => any);
13
- }
14
4
  /**
15
5
  * Class decorator to define a controller with optional configuration.
16
6
  *
@@ -32,33 +22,31 @@ interface ControllerConfig {
32
22
  *
33
23
  * @returns A class decorator function that enhances the controller class.
34
24
  */
35
- export declare function Controller(config: string | ControllerConfig, middlewares?: Array<Interceptor>): <T extends ControllerClass>(constructor: T) => {
25
+ export declare function Controller(config: string | ControllerConfig, middlewares?: Array<InterceptorCB>): <T extends ControllerClass>(constructor: T) => {
36
26
  new (...args: any[]): {
37
27
  [x: string]: any;
38
- executeControllerMethod: (controller: import("../types/index.js").ControllerInstance, propertyName: string, payload: any, response?: ServerResponse) => Promise<any>;
39
- getControllerMethods: (controller: import("../types/index.js").ControllerInstance) => {
40
- name: string;
41
- httpMethod: string;
42
- pattern: string;
43
- middlewares?: Array<(req: any, res?: ServerResponse) => any>;
44
- }[];
28
+ executeControllerMethod: (controller: ControllerInstance, propertyName: string, payload: any, request?: IncomingMessage, response?: ServerResponse) => Promise<any>;
29
+ getControllerMethods: (controller: ControllerInstance) => import("../types/index.js").ControllerMethods;
45
30
  getResponse(data: {
46
31
  controllerInstance: ControllerInstance;
47
32
  name: string;
48
33
  payload: any;
49
- interceptors: Array<(...args: any[]) => any | Promise<any>>;
34
+ interceptors: InterceptorCB[];
35
+ request?: IncomingMessage;
50
36
  response?: ServerResponse;
51
37
  }): Promise<{
52
38
  status: any;
53
39
  data: any;
54
40
  }>;
55
- handleRequest: (request: any, response?: ServerResponse) => Promise<{
56
- status: any;
57
- data: any;
58
- } | {
59
- status: number;
60
- message: string;
61
- }>;
41
+ handleRequest: (appRequest: AppRequest, request?: IncomingMessage, response?: ServerResponse) => Promise<any>;
42
+ routeWalker(context: RouteContext): Promise<any>;
43
+ getAllMethods(obj: any): string[];
44
+ findRouteInController(instance: any, path: string, route: string, method: string): {
45
+ name: string;
46
+ pathParams: Record<string, string>;
47
+ priority: number;
48
+ methodMiddlewares: any[];
49
+ methodInterceptors: any[];
50
+ };
62
51
  };
63
52
  } & T;
64
- export {};