quantum-flow 1.0.6 → 1.1.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 (46) hide show
  1. package/README.md +37 -22
  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
@@ -12,63 +12,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.Socket = void 0;
13
13
  const core_1 = require("quantum-flow/core");
14
14
  let Socket = class Socket {
15
- /**
16
- * 1. Приветствие при подключении
17
- */
18
15
  onConnection(event) {
19
- console.log(`✅ Подключился: ${event.client.id}`);
20
- // Отправляем приветствие ТОЛЬКО этому клиенту
21
- event.client.socket.send(JSON.stringify({
22
- type: 'welcome',
23
- data: { message: 'Добро пожаловать!' },
24
- }));
16
+ event.client.socket.send(JSON.stringify({ type: 'welcome', data: { message: 'welcome' } }));
25
17
  }
26
- /**
27
- * 2. @Subscribe - АВТОМАТИЧЕСКАЯ рассылка всем подписчикам
28
- * Не нужно использовать WebSocketService!
29
- */
30
18
  onChatMessage(event) {
31
- // Этот метод вызывается для КАЖДОГО подписчика
32
- // Сообщение УЖЕ автоматически разослано всем!
33
19
  const msg = event.message?.data;
34
- console.log(`💬 Сообщение в chat: ${msg?.text}`);
35
- // Можно добавить логику, но рассылать НЕ НУЖНО
36
- if (msg?.text.includes('плохое')) {
37
- // Если вернуть пустоту - сообщение не уйдет
20
+ if (msg?.text.includes('bad')) {
38
21
  return;
39
22
  }
40
- // Всё, сообщение само уйдет подписчикам!
41
23
  }
42
- /**
43
- * 3. @Subscribe для другой комнаты
44
- */
45
- onNewsMessage(event) {
46
- console.log(`📰 Новость: ${event.message?.data.title}`);
47
- // Автоматическая рассылка всем подписанным на 'news'
48
- }
49
- /**
50
- * 4. @OnMessage для команд (без WebSocketService)
51
- */
24
+ onNewsMessage(event) { }
52
25
  onPing(event) {
53
- // Отправляем ответ только этому клиенту
54
- event.client.socket.send(JSON.stringify({
55
- type: 'pong',
56
- data: { time: Date.now() },
57
- }));
26
+ event.client.socket.send(JSON.stringify({ type: 'pong', data: { time: Date.now() } }));
58
27
  }
59
- /**
60
- * 5. @OnMessage для подписки
61
- */
62
28
  onSubscribe(event) {
63
29
  const topic = event.message?.data.topic;
64
- console.log(`📌 Клиент ${event.client.id} подписался на ${topic}`);
65
- // Сервер сам сохранит подписку, ничего делать не нужно!
66
- // Просто подтверждаем
67
- event.client.socket.send(JSON.stringify({
68
- type: 'subscribed',
69
- topic,
70
- data: { success: true },
71
- }));
30
+ event.client.socket.send(JSON.stringify({ type: 'subscribed', topic, data: { success: true } }));
72
31
  }
73
32
  };
74
33
  exports.Socket = Socket;
@@ -1,3 +1,15 @@
1
+ import { IWebSocketService } from 'quantum-flow/core';
2
+ declare class DTO {
3
+ constructor();
4
+ name: string;
5
+ }
1
6
  export declare class User {
2
- test(body: any, query: any, headers: any, ws: any, resp: any): Promise<string>;
7
+ createUser(body: DTO, query: any, headers: any, ws: IWebSocketService, req: any, params: any, resp: any): Promise<{
8
+ body: DTO;
9
+ query: any;
10
+ headers: any;
11
+ params: any;
12
+ }>;
13
+ any(resp: any): Promise<string>;
3
14
  }
15
+ export {};
@@ -15,7 +15,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.User = void 0;
16
16
  const class_validator_1 = require("class-validator");
17
17
  const core_1 = require("quantum-flow/core");
18
- const http_1 = require("quantum-flow/http");
18
+ const userMetadata_1 = require("./userMetadata");
19
19
  class DTO {
20
20
  constructor() { }
21
21
  name;
@@ -25,31 +25,45 @@ __decorate([
25
25
  __metadata("design:type", String)
26
26
  ], DTO.prototype, "name", void 0);
27
27
  let User = class User {
28
- async test(body, query, headers, ws, resp) {
29
- console.log(resp.setHeader);
30
- resp.setHeader('Set-Cookie', ['token=; Path=/; Max-Age=0', 'userId=; Path=/; Max-Age=0']);
31
- return 'Test';
28
+ async createUser(body, query, headers, ws, req, params, resp) {
29
+ return { body, query, headers, params };
30
+ }
31
+ async any(resp) {
32
+ return 'done';
32
33
  }
33
34
  };
34
35
  exports.User = User;
35
36
  __decorate([
36
- (0, core_1.Status)(300),
37
- (0, core_1.USE)('/:nane'),
37
+ (0, core_1.Status)(201),
38
+ (0, core_1.PUT)(':id'),
38
39
  __param(0, (0, core_1.Body)(DTO)),
39
40
  __param(1, (0, core_1.Query)()),
40
41
  __param(2, (0, core_1.Headers)()),
41
42
  __param(3, (0, core_1.InjectWS)()),
42
- __param(4, (0, core_1.Response)()),
43
+ __param(4, (0, core_1.Request)()),
44
+ __param(5, (0, core_1.Params)()),
45
+ __param(6, (0, core_1.Response)()),
46
+ __metadata("design:type", Function),
47
+ __metadata("design:paramtypes", [DTO, Object, Object, Object, Object, Object, Object]),
48
+ __metadata("design:returntype", Promise)
49
+ ], User.prototype, "createUser", null);
50
+ __decorate([
51
+ (0, core_1.Status)(300),
52
+ (0, core_1.USE)(),
53
+ __param(0, (0, core_1.Response)()),
43
54
  __metadata("design:type", Function),
44
- __metadata("design:paramtypes", [Object, Object, Object, Object, Object]),
55
+ __metadata("design:paramtypes", [Object]),
45
56
  __metadata("design:returntype", Promise)
46
- ], User.prototype, "test", null);
57
+ ], User.prototype, "any", null);
47
58
  exports.User = User = __decorate([
48
59
  (0, core_1.Controller)({
49
60
  prefix: 'user',
61
+ controllers: [userMetadata_1.UserMetadata],
62
+ interceptor: (data, req, res) => {
63
+ return { data, intercepted: true };
64
+ },
50
65
  }),
51
- (0, http_1.Intercept)(() => {
52
- console.log('user interceptor');
53
- return 'intercepted';
66
+ (0, core_1.Catch)((err) => {
67
+ return { status: 401, err };
54
68
  })
55
69
  ], User);
@@ -0,0 +1,3 @@
1
+ export declare class UserMetadata {
2
+ getUserMetadata(params: any): Promise<any>;
3
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.UserMetadata = void 0;
16
+ const core_1 = require("quantum-flow/core");
17
+ let UserMetadata = class UserMetadata {
18
+ async getUserMetadata(params) {
19
+ return params;
20
+ }
21
+ };
22
+ exports.UserMetadata = UserMetadata;
23
+ __decorate([
24
+ (0, core_1.GET)('/:name'),
25
+ __param(0, (0, core_1.Params)()),
26
+ __metadata("design:type", Function),
27
+ __metadata("design:paramtypes", [Object]),
28
+ __metadata("design:returntype", Promise)
29
+ ], UserMetadata.prototype, "getUserMetadata", null);
30
+ exports.UserMetadata = UserMetadata = __decorate([
31
+ (0, core_1.Controller)({ prefix: 'metadata' })
32
+ ], UserMetadata);
@@ -9,40 +9,24 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  const core_1 = require("quantum-flow/core");
10
10
  const http_1 = require("quantum-flow/http");
11
11
  require("reflect-metadata");
12
- const socket_1 = require("./controllers/socket");
13
12
  const user_1 = require("./controllers/user");
14
13
  let Root = class Root {
15
14
  };
16
15
  Root = __decorate([
17
- (0, core_1.Controller)({
18
- prefix: 'api',
19
- controllers: [user_1.User, socket_1.Socket],
20
- interceptors: [
21
- (resp) => {
22
- return resp;
23
- },
24
- ],
25
- })
16
+ (0, core_1.Controller)({ prefix: 'api', controllers: [user_1.User] })
26
17
  ], Root);
27
18
  let App = class App {
28
19
  };
29
20
  App = __decorate([
30
21
  (0, http_1.Server)({
31
22
  controllers: [Root],
32
- websocket: {
33
- enabled: true,
34
- },
23
+ websocket: { enabled: true },
24
+ interceptor: (data) => data,
35
25
  }),
36
26
  (0, http_1.Port)(3000),
37
- (0, http_1.Host)('localhost'),
38
- (0, http_1.Use)((res) => res),
39
- (0, http_1.Intercept)((data, req, res) => {
40
- console.log(data, 'aaaaa', req);
41
- return data;
42
- }),
43
- (0, http_1.Catch)((r) => {
44
- return r;
45
- })
27
+ (0, core_1.Use)((data) => data),
28
+ (0, core_1.Use)((data) => data),
29
+ (0, core_1.Catch)((error) => ({ status: 400, error }))
46
30
  ], App);
47
31
  const server = new http_1.HttpServer(App);
48
32
  server.listen().catch(console.error);
@@ -1,15 +1,18 @@
1
- import { IncomingHttpHeaders, ServerResponse } from 'http';
1
+ import { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http';
2
2
  type P_Q = Record<string, string | undefined> | null | unknown;
3
- export type Request<B = unknown, Q extends P_Q = unknown, P extends P_Q = unknown> = {
4
- method: string;
3
+ export type AppRequest<B = unknown, Q extends P_Q = unknown, P extends P_Q = unknown> = {
4
+ method: HTTP_METHODS;
5
5
  url: URL;
6
6
  headers: IncomingHttpHeaders;
7
7
  query?: Q;
8
8
  params?: P;
9
9
  body: B;
10
+ rawBody: Buffer<ArrayBufferLike>;
10
11
  isBase64Encoded?: boolean;
12
+ cookies: Record<string, string>;
13
+ _startTime: number;
11
14
  };
12
- export type Router = (req: Request, res?: ServerResponse) => Promise<{
15
+ export type Router = (req: AppRequest, res?: ServerResponse) => Promise<{
13
16
  status: number;
14
17
  data: any;
15
18
  message?: string;
@@ -35,13 +38,34 @@ export type AxiosQuery = {
35
38
  export interface IController {
36
39
  handleRequest: Router;
37
40
  }
38
- export type Middleware = (req: Request, res?: ServerResponse) => Promise<Request> | Request;
39
- export type Interceptor = (data: any, req?: Request, res?: ServerResponse) => Promise<unknown> | unknown;
40
- export type ParamDecoratorType = 'body' | 'params' | 'query' | 'request' | 'headers' | 'cookies' | 'response' | 'multipart';
41
+ export type MiddlewareCB = (appRequest: AppRequest, request?: IncomingMessage, respinse?: ServerResponse) => Promise<AppRequest> | AppRequest;
42
+ export type InterceptorCB = (data: any, req?: IncomingMessage, res?: ServerResponse) => Promise<unknown> | unknown;
43
+ export type ErrorCB = (error: Error, req?: IncomingMessage, res?: ServerResponse) => Promise<ResponseWithStatus> | ResponseWithStatus;
44
+ export type ParamDecoratorType = 'body' | 'params' | 'query' | 'request' | 'headers' | 'cookies' | 'response' | 'multipart' | 'event' | 'context';
41
45
  export interface ParamMetadata {
42
46
  index: number;
43
47
  type: ParamDecoratorType;
44
48
  dto?: any;
45
49
  name?: string;
46
50
  }
51
+ export interface ParamMetadata {
52
+ index: number;
53
+ type: ParamDecoratorType;
54
+ dto?: any;
55
+ name?: string;
56
+ }
57
+ export type ResponseWithStatus = {
58
+ status: number;
59
+ [key: string]: any;
60
+ };
61
+ export declare enum HTTP_METHODS {
62
+ USE = "USE",
63
+ GET = "GET",
64
+ POST = "POST",
65
+ PATCH = "PATCH",
66
+ DELETE = "DELETE",
67
+ PUT = "PUT",
68
+ OPTIONS = "OPTIONS",
69
+ HEAD = "HEAD"
70
+ }
47
71
  export {};
@@ -1,2 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HTTP_METHODS = void 0;
4
+ var HTTP_METHODS;
5
+ (function (HTTP_METHODS) {
6
+ HTTP_METHODS["USE"] = "USE";
7
+ HTTP_METHODS["GET"] = "GET";
8
+ HTTP_METHODS["POST"] = "POST";
9
+ HTTP_METHODS["PATCH"] = "PATCH";
10
+ HTTP_METHODS["DELETE"] = "DELETE";
11
+ HTTP_METHODS["PUT"] = "PUT";
12
+ HTTP_METHODS["OPTIONS"] = "OPTIONS";
13
+ HTTP_METHODS["HEAD"] = "HEAD";
14
+ })(HTTP_METHODS || (exports.HTTP_METHODS = HTTP_METHODS = {}));
@@ -1,4 +1,37 @@
1
+ import { IncomingMessage, ServerResponse } from 'http';
2
+ import { AppRequest, ErrorCB, HTTP_METHODS, InterceptorCB, MiddlewareCB } from './common';
1
3
  export type ControllerClass = {
2
4
  new (...args: any[]): any;
3
5
  };
4
6
  export type ControllerInstance = InstanceType<ControllerClass>;
7
+ export type ControllerMethods = Array<{
8
+ name: string;
9
+ httpMethod: HTTP_METHODS;
10
+ pattern: string;
11
+ middlewares?: MiddlewareCB[];
12
+ }>;
13
+ export type ControllerMetadata = {
14
+ routePrefix: string;
15
+ middlewares: MiddlewareCB[];
16
+ interceptor?: InterceptorCB;
17
+ subControllers: ControllerClass[];
18
+ errorHandler?: ErrorCB;
19
+ };
20
+ export interface ControllerConfig {
21
+ prefix: string;
22
+ middlewares?: Array<MiddlewareCB>;
23
+ controllers?: ControllerClass[];
24
+ interceptor?: InterceptorCB;
25
+ }
26
+ export type RouteContext = {
27
+ controllerInstance: any;
28
+ controllerMeta: ControllerMetadata;
29
+ path: string;
30
+ method: string;
31
+ appRequest: AppRequest;
32
+ request?: IncomingMessage;
33
+ response?: ServerResponse;
34
+ middlewareChain: MiddlewareCB[];
35
+ interceptorChain: InterceptorCB[];
36
+ subPath: string;
37
+ };
@@ -1,18 +1,14 @@
1
+ import { ErrorCB, InterceptorCB, MiddlewareCB } from './common';
1
2
  export interface ServerConfig {
2
3
  port?: number;
3
4
  host?: string;
4
- globalMiddlewares?: any[];
5
- globalInterceptors?: any[];
6
- globalErrorHandler?: any;
7
- controllers?: any[];
5
+ middlewares?: MiddlewareCB[];
6
+ interceptor?: InterceptorCB;
7
+ errorHandler?: ErrorCB;
8
+ controllers?: (new (...args: any[]) => any)[];
8
9
  websocket?: {
9
10
  enabled: boolean;
10
11
  path?: string;
11
12
  lazy?: boolean;
12
13
  };
13
14
  }
14
- export type Conf = ServerConfig & {
15
- globalMiddlewares?: any[];
16
- globalInterceptors?: any[];
17
- globalErrorHandler?: any;
18
- };
@@ -7,7 +7,6 @@ export interface LambdaRequest {
7
7
  body: any;
8
8
  params: Record<string, string>;
9
9
  cookies: Record<string, string>;
10
- raw: APIGatewayProxyEvent;
11
10
  context: Context;
12
11
  isBase64Encoded: boolean;
13
12
  requestId: string;
@@ -15,6 +14,7 @@ export interface LambdaRequest {
15
14
  sourceIp: string;
16
15
  userAgent: string;
17
16
  url: URL;
17
+ event: APIGatewayProxyEvent;
18
18
  }
19
19
  export interface LambdaResponse {
20
20
  statusCode: number;
@@ -24,3 +24,10 @@ export interface LambdaResponse {
24
24
  multiValueHeaders?: Record<string, string[]>;
25
25
  cookies?: string[];
26
26
  }
27
+ export interface LambdaApp {
28
+ beforeStart?: () => void;
29
+ }
30
+ export interface Lambda {
31
+ beforeStart?: () => Promise<void>;
32
+ handleRequest(request: any): Promise<any>;
33
+ }
@@ -1,9 +1,4 @@
1
- import { ControllerInstance } from '../types/index.js';
2
- import { ServerResponse } from 'http';
3
- export declare const executeControllerMethod: (controller: ControllerInstance, propertyName: string, payload: any, response?: ServerResponse) => Promise<any>;
4
- export declare const getControllerMethods: (controller: ControllerInstance) => {
5
- name: string;
6
- httpMethod: string;
7
- pattern: string;
8
- middlewares?: Array<(req: any, res?: ServerResponse) => any>;
9
- }[];
1
+ import { ControllerInstance, ControllerMethods } from '../types/index.js';
2
+ import { IncomingMessage, ServerResponse } from 'http';
3
+ export declare const executeControllerMethod: (controller: ControllerInstance, propertyName: string, payload: any, request?: IncomingMessage, response?: ServerResponse) => Promise<any>;
4
+ export declare const getControllerMethods: (controller: ControllerInstance) => ControllerMethods;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getControllerMethods = exports.executeControllerMethod = void 0;
4
+ const _types_1 = require("../types/index.js");
4
5
  const _utils_1 = require("./index.js");
5
6
  const WebsocetService_1 = require("../app/http/websocket/WebsocetService");
6
7
  const validate_1 = require("./validate");
@@ -25,7 +26,7 @@ const getBodyAndMultipart = (payload) => {
25
26
  }
26
27
  return { multipart, body };
27
28
  };
28
- const executeControllerMethod = async (controller, propertyName, payload, response) => {
29
+ const executeControllerMethod = async (controller, propertyName, payload, request, response) => {
29
30
  const fn = controller[propertyName];
30
31
  if (typeof fn !== 'function')
31
32
  return null;
@@ -67,15 +68,15 @@ const executeControllerMethod = async (controller, propertyName, payload, respon
67
68
  if (param.type === 'request') {
68
69
  value = payload;
69
70
  }
70
- if (param.type === 'response') {
71
- value = response;
72
- }
73
- if (param.type === 'response') {
74
- value = response;
71
+ if (param.type === 'request') {
72
+ value = request;
75
73
  }
76
74
  if (param.type === 'body') {
77
75
  value = body;
78
76
  }
77
+ if (param.type === 'response') {
78
+ value = response;
79
+ }
79
80
  if (_constants_1.TO_VALIDATE.includes(param.type)) {
80
81
  value = await (0, validate_1.validate)(param.dto, value);
81
82
  }
@@ -106,6 +107,6 @@ const getControllerMethods = (controller) => {
106
107
  }
107
108
  proto = Object.getPrototypeOf(proto);
108
109
  }
109
- return methods;
110
+ return methods.sort((a, b) => (a.httpMethod === _types_1.HTTP_METHODS.USE ? 1 : -1));
110
111
  };
111
112
  exports.getControllerMethods = getControllerMethods;
@@ -0,0 +1,2 @@
1
+ import { ParamDecoratorType } from '../types/index.js';
2
+ export declare function createParamDecorator(type: ParamDecoratorType, dto?: any, name?: string): (target: any, propertyKey: string | symbol, parameterIndex: number) => void;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createParamDecorator = createParamDecorator;
4
+ const _constants_1 = require("../constants.js");
5
+ function createParamDecorator(type, dto, name) {
6
+ return function (target, propertyKey, parameterIndex) {
7
+ const existingParams = Reflect.getMetadata(_constants_1.PARAM_METADATA_KEY, target, propertyKey) || [];
8
+ existingParams.push({ index: parameterIndex, type, dto, name });
9
+ existingParams.sort((a, b) => a.index - b.index);
10
+ Reflect.defineMetadata(_constants_1.PARAM_METADATA_KEY, existingParams, target, propertyKey);
11
+ const saved = Reflect.getMetadata(_constants_1.PARAM_METADATA_KEY, target, propertyKey);
12
+ };
13
+ }
@@ -1 +1,5 @@
1
- export declare const matchRoute: (routePattern: string, actualPath: string) => Record<string, string> | null;
1
+ import { InterceptorCB, MiddlewareCB } from '../types/index.js';
2
+ export declare function matchRoute(pattern: string, path: string): Record<string, string> | null;
3
+ export declare function buildRoutePattern(parts: string[]): string;
4
+ export declare function mergeMiddlewares(...middlewareLists: MiddlewareCB[][]): MiddlewareCB[];
5
+ export declare function mergeInterceptors(...interceptorLists: InterceptorCB[][]): InterceptorCB[];
@@ -1,24 +1,61 @@
1
1
  "use strict";
2
- /* eslint-disable @typescript-eslint/no-explicit-any */
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.matchRoute = void 0;
5
- const matchRoute = (routePattern, actualPath) => {
6
- const routeParts = routePattern.split('/').filter(Boolean);
7
- const pathParts = actualPath.split('/').filter(Boolean);
8
- if (routeParts.length !== pathParts.length)
9
- return null;
3
+ exports.matchRoute = matchRoute;
4
+ exports.buildRoutePattern = buildRoutePattern;
5
+ exports.mergeMiddlewares = mergeMiddlewares;
6
+ exports.mergeInterceptors = mergeInterceptors;
7
+ function matchRoute(pattern, path) {
8
+ pattern = pattern.replace(/^\/+|\/+$/g, '');
9
+ path = path.replace(/^\/+|\/+$/g, '');
10
+ const patternSegments = pattern.split('/').filter(Boolean);
11
+ const pathSegments = path.split('/').filter(Boolean);
10
12
  const params = {};
11
- for (let i = 0; i < routeParts.length; i++) {
12
- const routePart = routeParts[i];
13
- const pathPart = pathParts[i];
14
- if (routePart.startsWith(':')) {
15
- const paramName = routePart.slice(1);
16
- params[paramName] = decodeURIComponent(pathPart);
13
+ let i = 0;
14
+ let j = 0;
15
+ while (i < patternSegments.length && j < pathSegments.length) {
16
+ const patternSegment = patternSegments[i];
17
+ const pathSegment = pathSegments[j];
18
+ if (patternSegment === '*') {
19
+ params['*'] = pathSegments.slice(j).join('/');
20
+ return params;
21
+ }
22
+ if (patternSegment.startsWith(':')) {
23
+ const paramName = patternSegment.slice(1);
24
+ params[paramName] = pathSegment;
25
+ i++;
26
+ j++;
27
+ continue;
17
28
  }
18
- else if (routePart !== pathPart) {
29
+ if (patternSegment !== pathSegment) {
19
30
  return null;
20
31
  }
32
+ i++;
33
+ j++;
21
34
  }
22
- return params;
23
- };
24
- exports.matchRoute = matchRoute;
35
+ while (i < patternSegments.length) {
36
+ const patternSegment = patternSegments[i];
37
+ if (patternSegment === '*') {
38
+ params['*'] = '';
39
+ i++;
40
+ }
41
+ else if (patternSegment.startsWith(':')) {
42
+ return null;
43
+ }
44
+ else {
45
+ return null;
46
+ }
47
+ }
48
+ if (j < pathSegments.length) {
49
+ return null;
50
+ }
51
+ return Object.keys(params).length > 0 ? params : {};
52
+ }
53
+ function buildRoutePattern(parts) {
54
+ return parts.filter(Boolean).join('/').replace(/\/+/g, '/');
55
+ }
56
+ function mergeMiddlewares(...middlewareLists) {
57
+ return middlewareLists.flat();
58
+ }
59
+ function mergeInterceptors(...interceptorLists) {
60
+ return interceptorLists.flat();
61
+ }
@@ -5,3 +5,4 @@ export * from './parsers';
5
5
  export * from './server';
6
6
  export * from './transform';
7
7
  export * from './validate';
8
+ export * from './endpoint';
@@ -21,3 +21,4 @@ __exportStar(require("./parsers"), exports);
21
21
  __exportStar(require("./server"), exports);
22
22
  __exportStar(require("./transform"), exports);
23
23
  __exportStar(require("./validate"), exports);
24
+ __exportStar(require("./endpoint"), exports);
@@ -7,10 +7,14 @@ const resolveConfig = (configOrClass) => {
7
7
  if (configOrClass && typeof configOrClass === 'function') {
8
8
  const decoratorConfig = Reflect.getMetadata(_constants_1.SERVER_CONFIG_KEY, configOrClass) || {};
9
9
  const controllers = Reflect.getMetadata(_constants_1.SERVER_MODULES_KEY, configOrClass) || [];
10
+ const errorHandler = Reflect.getMetadata(_constants_1.CATCH, configOrClass);
11
+ const interceptors = Reflect.getMetadata(_constants_1.INTECEPT, configOrClass);
10
12
  config = {
11
13
  port: 3000,
12
14
  host: 'localhost',
13
15
  ...decoratorConfig,
16
+ errorHandler,
17
+ interceptors,
14
18
  controllers: [...controllers, ...(decoratorConfig.controllers || [])],
15
19
  };
16
20
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "quantum-flow",
3
- "version": "1.0.6",
3
+ "version": "1.1.0",
4
4
  "description": "Decorator-based API framework",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",