clear-router 2.1.12 → 2.2.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 +4 -4
- package/dist/core/index.cjs +4 -0
- package/dist/core/index.d.cts +2 -0
- package/dist/core/index.d.mts +2 -0
- package/dist/core/index.mjs +3 -0
- package/dist/express/index.cjs +86 -247
- package/dist/express/index.d.cts +68 -97
- package/dist/express/index.d.mts +68 -97
- package/dist/express/index.mjs +86 -247
- package/dist/h3/index.cjs +88 -242
- package/dist/h3/index.d.cts +72 -93
- package/dist/h3/index.d.mts +72 -93
- package/dist/h3/index.mjs +88 -242
- package/dist/index.cjs +342 -0
- package/dist/index.d.cts +184 -38
- package/dist/index.d.mts +184 -38
- package/dist/index.mjs +343 -1
- package/dist/router-BNVIrTi3.cjs +397 -0
- package/dist/router-BiCuy5TZ.mjs +392 -0
- package/dist/router-C1jVRytA.d.mts +311 -0
- package/dist/router-CZIh1ZPJ.d.cts +311 -0
- package/dist/types/Route.d.mts +4 -4
- package/package.json +6 -2
- package/dist/Route-BbPXcDGX.mjs +0 -50
- package/dist/Route-DhC4kNPX.cjs +0 -62
- package/dist/basic-C_1O6RVq.d.cts +0 -138
- package/dist/basic-cLeny2Zk.d.mts +0 -138
package/dist/index.d.mts
CHANGED
|
@@ -1,48 +1,32 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1
2
|
import { NextFunction, Request, Response as Response$1 } from "express";
|
|
2
|
-
import {
|
|
3
|
+
import { Middleware as Middleware$1 } from "h3";
|
|
3
4
|
|
|
4
|
-
//#region types/h3.d.ts
|
|
5
|
-
type HttpRequest = H3Event['req'] & {
|
|
6
|
-
getBody: () => Record<string, any>;
|
|
7
|
-
};
|
|
8
|
-
/**
|
|
9
|
-
* HTTP context passed to route handlers
|
|
10
|
-
*/
|
|
11
|
-
type HttpContext = Omit<H3Event, 'req'> & {
|
|
12
|
-
req: HttpRequest;
|
|
13
|
-
};
|
|
14
|
-
/**
|
|
15
|
-
* Route handler function type
|
|
16
|
-
*/
|
|
17
|
-
type RouteHandler = (
|
|
18
|
-
/**
|
|
19
|
-
* H3 event context
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
ctx: HttpContext,
|
|
23
|
-
/**
|
|
24
|
-
* ClearRequest instance
|
|
25
|
-
*/
|
|
26
|
-
|
|
27
|
-
req: ClearRequest) => any | Promise<any>;
|
|
28
|
-
/**
|
|
29
|
-
* Handler can be either a function or controller reference
|
|
30
|
-
*/
|
|
31
|
-
type Handler = RouteHandler | ControllerHandler;
|
|
32
|
-
//#endregion
|
|
33
5
|
//#region types/basic.d.ts
|
|
34
|
-
/**
|
|
35
|
-
* Controller method reference
|
|
36
|
-
*/
|
|
37
|
-
type ControllerHandler = [any, string];
|
|
38
6
|
/**
|
|
39
7
|
* HTTP methods supported by the router
|
|
40
8
|
*/
|
|
41
9
|
type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
|
|
10
|
+
/**
|
|
11
|
+
* Common controller action names
|
|
12
|
+
*/
|
|
13
|
+
type ControllerAction = 'index' | 'show' | 'create' | 'update' | 'destroy';
|
|
42
14
|
/**
|
|
43
15
|
* Generic Object type for request data
|
|
44
16
|
*/
|
|
45
17
|
type RequestData = Record<string, any>;
|
|
18
|
+
type ApiResourceMiddleware<M extends Middleware | Middleware$1> = M | M[] | { [K in ControllerAction]?: M | M[] };
|
|
19
|
+
interface RouterConfig {
|
|
20
|
+
/**
|
|
21
|
+
* Configuration for method override functionality, allowing clients to use a
|
|
22
|
+
* specific header or body parameter to override the HTTP method.
|
|
23
|
+
*/
|
|
24
|
+
methodOverride?: {
|
|
25
|
+
/** Whether method override is enabled */enabled?: boolean; /** Keys in the request body to check for method override */
|
|
26
|
+
bodyKeys?: string[] | string; /** Keys in the request headers to check for method override */
|
|
27
|
+
headerKeys?: string[] | string;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
46
30
|
//#endregion
|
|
47
31
|
//#region types/express.d.ts
|
|
48
32
|
/**
|
|
@@ -51,7 +35,7 @@ type RequestData = Record<string, any>;
|
|
|
51
35
|
type Middleware = (req: Request, res: Response$1, next: NextFunction) => any | Promise<any>;
|
|
52
36
|
//#endregion
|
|
53
37
|
//#region src/Route.d.ts
|
|
54
|
-
declare class Route<X = any, M = Middleware$1 | Middleware> {
|
|
38
|
+
declare class Route<X = any, M = Middleware$1 | Middleware, H = any> {
|
|
55
39
|
ctx: X;
|
|
56
40
|
body: RequestData;
|
|
57
41
|
query: RequestData;
|
|
@@ -59,13 +43,13 @@ declare class Route<X = any, M = Middleware$1 | Middleware> {
|
|
|
59
43
|
clearRequest: ClearRequest;
|
|
60
44
|
methods: HttpMethod[];
|
|
61
45
|
path: string;
|
|
62
|
-
handler:
|
|
46
|
+
handler: H;
|
|
63
47
|
middlewares: M[];
|
|
64
48
|
controllerName?: string;
|
|
65
49
|
actionName?: string;
|
|
66
50
|
handlerType: 'function' | 'controller';
|
|
67
51
|
middlewareCount: number;
|
|
68
|
-
constructor(methods: HttpMethod[], path: string, handler:
|
|
52
|
+
constructor(methods: HttpMethod[], path: string, handler: H, middlewares?: M[]);
|
|
69
53
|
}
|
|
70
54
|
//#endregion
|
|
71
55
|
//#region src/ClearRequest.d.ts
|
|
@@ -97,4 +81,166 @@ declare abstract class Controller<X = any> {
|
|
|
97
81
|
clearRequest: ClearRequest;
|
|
98
82
|
}
|
|
99
83
|
//#endregion
|
|
100
|
-
|
|
84
|
+
//#region src/core/router.d.ts
|
|
85
|
+
/**
|
|
86
|
+
* @class clear-router CoreRouter
|
|
87
|
+
* @description Core routing logic for clear-router, shared between all supported adapters (Express.js, H3, etc.)
|
|
88
|
+
* @author 3m1n3nc3
|
|
89
|
+
* @repository https://github.com/toneflix/clear-router
|
|
90
|
+
*/
|
|
91
|
+
declare abstract class CoreRouter {
|
|
92
|
+
static config: RouterConfig;
|
|
93
|
+
protected static groupContext: AsyncLocalStorage<{
|
|
94
|
+
prefix: string;
|
|
95
|
+
groupMiddlewares: any[];
|
|
96
|
+
}>;
|
|
97
|
+
static routes: Array<Route<any, any, any>>;
|
|
98
|
+
static routesByPathMethod: Record<string, Route<any, any, any>>;
|
|
99
|
+
static routesByMethod: { [method in Uppercase<HttpMethod>]?: Array<Route<any, any, any>> };
|
|
100
|
+
static prefix: string;
|
|
101
|
+
static groupMiddlewares: any[];
|
|
102
|
+
static globalMiddlewares: any[];
|
|
103
|
+
protected static ensureState(this: any): void;
|
|
104
|
+
/**
|
|
105
|
+
* Normalizes a path by ensuring it starts with a single slash and does not have trailing
|
|
106
|
+
* slashes, while preserving dynamic segments and parameters.
|
|
107
|
+
*
|
|
108
|
+
* @param path The path to normalize.
|
|
109
|
+
* @returns The normalized path.
|
|
110
|
+
*/
|
|
111
|
+
static normalizePath(path: string): string;
|
|
112
|
+
/**
|
|
113
|
+
* Configures the router with the given options, such as method override settings.
|
|
114
|
+
*
|
|
115
|
+
* @param this
|
|
116
|
+
* @param options
|
|
117
|
+
* @returns
|
|
118
|
+
*/
|
|
119
|
+
static configure(this: any, options?: RouterConfig): void;
|
|
120
|
+
protected static resolveMethodOverride(this: any, method: string, headers: Headers | Record<string, any>, body: unknown): HttpMethod | null;
|
|
121
|
+
/**
|
|
122
|
+
* Adds a new route to the router with the specified methods, path, handler, and middlewares.
|
|
123
|
+
*
|
|
124
|
+
* @param this
|
|
125
|
+
* @param methods
|
|
126
|
+
* @param path
|
|
127
|
+
* @param handler
|
|
128
|
+
* @param middlewares
|
|
129
|
+
*/
|
|
130
|
+
static add(this: any, methods: HttpMethod | HttpMethod[], path: string, handler: any, middlewares?: any[] | any): void;
|
|
131
|
+
/**
|
|
132
|
+
* Adds a new API resource route to the router for the specified base path and controller, with
|
|
133
|
+
* options to include/exclude specific actions and apply middlewares.
|
|
134
|
+
*
|
|
135
|
+
* @param this
|
|
136
|
+
* @param basePath
|
|
137
|
+
* @param controller
|
|
138
|
+
* @param options
|
|
139
|
+
*/
|
|
140
|
+
static apiResource(this: any, basePath: string, controller: any, options?: {
|
|
141
|
+
only?: ControllerAction[];
|
|
142
|
+
except?: ControllerAction[];
|
|
143
|
+
middlewares?: ApiResourceMiddleware<any>;
|
|
144
|
+
}): void;
|
|
145
|
+
/**
|
|
146
|
+
* Adds a new GET route to the router with the specified path, handler, and optional middlewares.
|
|
147
|
+
*
|
|
148
|
+
* @param this The router instance.
|
|
149
|
+
* @param path The path for the GET route.
|
|
150
|
+
* @param handler The handler function for the GET route.
|
|
151
|
+
* @param middlewares Optional middlewares to apply to the GET route.
|
|
152
|
+
*/
|
|
153
|
+
static get(this: any, path: string, handler: any, middlewares?: any[] | any): void;
|
|
154
|
+
/**
|
|
155
|
+
* Adds a new POST route to the router with the specified path, handler, and optional middlewares.
|
|
156
|
+
*
|
|
157
|
+
* @param this
|
|
158
|
+
* @param path
|
|
159
|
+
* @param handler
|
|
160
|
+
* @param middlewares
|
|
161
|
+
*/
|
|
162
|
+
static post(this: any, path: string, handler: any, middlewares?: any[] | any): void;
|
|
163
|
+
/**
|
|
164
|
+
* Adds a new PUT route to the router with the specified path, handler, and optional middlewares.
|
|
165
|
+
*
|
|
166
|
+
* @param this
|
|
167
|
+
* @param path
|
|
168
|
+
* @param handler
|
|
169
|
+
* @param middlewares
|
|
170
|
+
*/
|
|
171
|
+
static put(this: any, path: string, handler: any, middlewares?: any[] | any): void;
|
|
172
|
+
/**
|
|
173
|
+
* Adds a new DELETE route to the router with the specified path, handler, and optional middlewares.
|
|
174
|
+
*
|
|
175
|
+
* @param this
|
|
176
|
+
* @param path
|
|
177
|
+
* @param handler
|
|
178
|
+
* @param middlewares
|
|
179
|
+
*/
|
|
180
|
+
static delete(this: any, path: string, handler: any, middlewares?: any[] | any): void;
|
|
181
|
+
/**
|
|
182
|
+
* Adds a new PATCH route to the router with the specified path, handler, and optional middlewares.
|
|
183
|
+
*
|
|
184
|
+
* @param this
|
|
185
|
+
* @param path
|
|
186
|
+
* @param handler
|
|
187
|
+
* @param middlewares
|
|
188
|
+
*/
|
|
189
|
+
static patch(this: any, path: string, handler: any, middlewares?: any[] | any): void;
|
|
190
|
+
/**
|
|
191
|
+
* Adds a new OPTIONS route to the router with the specified path, handler, and optional middlewares.
|
|
192
|
+
*
|
|
193
|
+
* @param this
|
|
194
|
+
* @param path
|
|
195
|
+
* @param handler
|
|
196
|
+
* @param middlewares
|
|
197
|
+
*/
|
|
198
|
+
static options(this: any, path: string, handler: any, middlewares?: any[] | any): void;
|
|
199
|
+
/**
|
|
200
|
+
* Adds a new HEAD route to the router with the specified path, handler, and optional middlewares.
|
|
201
|
+
*
|
|
202
|
+
* @param this
|
|
203
|
+
* @param path
|
|
204
|
+
* @param handler
|
|
205
|
+
* @param middlewares
|
|
206
|
+
*/
|
|
207
|
+
static head(this: any, path: string, handler: any, middlewares?: any[] | any): void;
|
|
208
|
+
/**
|
|
209
|
+
* Defines a group of routes with a common prefix and optional middlewares, allowing for better
|
|
210
|
+
* organization and reuse of route configurations.
|
|
211
|
+
*
|
|
212
|
+
* @param this
|
|
213
|
+
* @param prefix
|
|
214
|
+
* @param callback
|
|
215
|
+
* @param middlewares
|
|
216
|
+
*/
|
|
217
|
+
static group(this: any, prefix: string, callback: () => void | Promise<void>, middlewares?: any[]): Promise<void>;
|
|
218
|
+
/**
|
|
219
|
+
* Adds global middlewares to the router, which will be applied to all routes.
|
|
220
|
+
*
|
|
221
|
+
* @param this
|
|
222
|
+
* @param middlewares
|
|
223
|
+
* @param callback
|
|
224
|
+
*/
|
|
225
|
+
static middleware(this: any, middlewares: any[], callback: () => void): void;
|
|
226
|
+
/**
|
|
227
|
+
* Retrieves all registered routes in the router, optionally organized by path or method
|
|
228
|
+
* for easier access and management.
|
|
229
|
+
*
|
|
230
|
+
* @param this
|
|
231
|
+
*/
|
|
232
|
+
static allRoutes(this: any): Array<Route<any, any, any>>;
|
|
233
|
+
static allRoutes(this: any, type: 'path'): Record<string, Route<any, any, any>>;
|
|
234
|
+
static allRoutes(this: any, type: 'method'): { [method in Uppercase<HttpMethod>]?: Array<Route<any, any, any>> };
|
|
235
|
+
protected static resolveHandler(route: Route<any, any, any>): {
|
|
236
|
+
handlerFunction: ((ctx: any, req: ClearRequest) => any | Promise<any>) | null;
|
|
237
|
+
instance: Controller<any> | null;
|
|
238
|
+
};
|
|
239
|
+
protected static bindRequestToInstance(ctx: any, instance: Controller<any> | Route<any, any, any> | null, route: Route<any, any, any>, payload: {
|
|
240
|
+
body: Record<string, any>;
|
|
241
|
+
query: Record<string, any>;
|
|
242
|
+
params: Record<string, any>;
|
|
243
|
+
}): void;
|
|
244
|
+
}
|
|
245
|
+
//#endregion
|
|
246
|
+
export { ClearRequest, Controller, CoreRouter, Route };
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
|
|
1
3
|
//#region src/ClearRequest.ts
|
|
2
4
|
var ClearRequest = class {
|
|
3
5
|
/**
|
|
@@ -57,4 +59,344 @@ var Route = class {
|
|
|
57
59
|
};
|
|
58
60
|
|
|
59
61
|
//#endregion
|
|
60
|
-
|
|
62
|
+
//#region src/core/router.ts
|
|
63
|
+
/**
|
|
64
|
+
* @class clear-router CoreRouter
|
|
65
|
+
* @description Core routing logic for clear-router, shared between all supported adapters (Express.js, H3, etc.)
|
|
66
|
+
* @author 3m1n3nc3
|
|
67
|
+
* @repository https://github.com/toneflix/clear-router
|
|
68
|
+
*/
|
|
69
|
+
var CoreRouter = class {
|
|
70
|
+
static config = { methodOverride: {
|
|
71
|
+
enabled: true,
|
|
72
|
+
bodyKeys: ["_method"],
|
|
73
|
+
headerKeys: ["x-http-method"]
|
|
74
|
+
} };
|
|
75
|
+
static groupContext = new AsyncLocalStorage();
|
|
76
|
+
static routes = [];
|
|
77
|
+
static routesByPathMethod = {};
|
|
78
|
+
static routesByMethod = {};
|
|
79
|
+
static prefix = "";
|
|
80
|
+
static groupMiddlewares = [];
|
|
81
|
+
static globalMiddlewares = [];
|
|
82
|
+
static ensureState() {
|
|
83
|
+
if (!Object.prototype.hasOwnProperty.call(this, "config")) this.config = { methodOverride: {
|
|
84
|
+
enabled: true,
|
|
85
|
+
bodyKeys: ["_method"],
|
|
86
|
+
headerKeys: ["x-http-method"]
|
|
87
|
+
} };
|
|
88
|
+
if (!Object.prototype.hasOwnProperty.call(this, "groupContext")) this.groupContext = new AsyncLocalStorage();
|
|
89
|
+
if (!Object.prototype.hasOwnProperty.call(this, "routes")) this.routes = [];
|
|
90
|
+
if (!Object.prototype.hasOwnProperty.call(this, "routesByPathMethod")) this.routesByPathMethod = {};
|
|
91
|
+
if (!Object.prototype.hasOwnProperty.call(this, "routesByMethod")) this.routesByMethod = {};
|
|
92
|
+
if (!Object.prototype.hasOwnProperty.call(this, "prefix")) this.prefix = "";
|
|
93
|
+
if (!Object.prototype.hasOwnProperty.call(this, "groupMiddlewares")) this.groupMiddlewares = [];
|
|
94
|
+
if (!Object.prototype.hasOwnProperty.call(this, "globalMiddlewares")) this.globalMiddlewares = [];
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Normalizes a path by ensuring it starts with a single slash and does not have trailing
|
|
98
|
+
* slashes, while preserving dynamic segments and parameters.
|
|
99
|
+
*
|
|
100
|
+
* @param path The path to normalize.
|
|
101
|
+
* @returns The normalized path.
|
|
102
|
+
*/
|
|
103
|
+
static normalizePath(path) {
|
|
104
|
+
return "/" + path.split("/").filter(Boolean).join("/");
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Configures the router with the given options, such as method override settings.
|
|
108
|
+
*
|
|
109
|
+
* @param this
|
|
110
|
+
* @param options
|
|
111
|
+
* @returns
|
|
112
|
+
*/
|
|
113
|
+
static configure(options) {
|
|
114
|
+
this.ensureState();
|
|
115
|
+
if (!this.config.methodOverride) this.config.methodOverride = {
|
|
116
|
+
enabled: true,
|
|
117
|
+
bodyKeys: ["_method"],
|
|
118
|
+
headerKeys: ["x-http-method"]
|
|
119
|
+
};
|
|
120
|
+
const override = options?.methodOverride;
|
|
121
|
+
if (!override) return;
|
|
122
|
+
if (typeof override.enabled === "boolean") this.config.methodOverride.enabled = override.enabled;
|
|
123
|
+
const bodyKeys = override.bodyKeys;
|
|
124
|
+
if (typeof bodyKeys !== "undefined") this.config.methodOverride.bodyKeys = (Array.isArray(bodyKeys) ? bodyKeys : [bodyKeys]).map((e) => String(e).trim()).filter(Boolean);
|
|
125
|
+
const headerKeys = override.headerKeys;
|
|
126
|
+
if (typeof headerKeys !== "undefined") this.config.methodOverride.headerKeys = (Array.isArray(headerKeys) ? headerKeys : [headerKeys]).map((e) => String(e).trim().toLowerCase()).filter(Boolean);
|
|
127
|
+
}
|
|
128
|
+
static resolveMethodOverride(method, headers, body) {
|
|
129
|
+
this.ensureState();
|
|
130
|
+
if (!this.config.methodOverride?.enabled || method.toLowerCase() !== "post") return null;
|
|
131
|
+
let override;
|
|
132
|
+
const headerValueFor = (key) => {
|
|
133
|
+
if (typeof headers.get === "function") return headers.get(key);
|
|
134
|
+
const value = headers?.[key];
|
|
135
|
+
return Array.isArray(value) ? value[0] : value;
|
|
136
|
+
};
|
|
137
|
+
for (const key of this.config.methodOverride?.headerKeys || []) {
|
|
138
|
+
const value = headerValueFor(key);
|
|
139
|
+
if (value) {
|
|
140
|
+
override = value;
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (!override && body && typeof body === "object") for (const key of this.config.methodOverride?.bodyKeys || []) {
|
|
145
|
+
const value = body[key];
|
|
146
|
+
if (typeof value !== "undefined" && value !== null && value !== "") {
|
|
147
|
+
override = value;
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const normalized = String(override || "").trim().toLowerCase();
|
|
152
|
+
if (!normalized) return null;
|
|
153
|
+
if ([
|
|
154
|
+
"put",
|
|
155
|
+
"patch",
|
|
156
|
+
"delete",
|
|
157
|
+
"post"
|
|
158
|
+
].includes(normalized)) return normalized;
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Adds a new route to the router with the specified methods, path, handler, and middlewares.
|
|
163
|
+
*
|
|
164
|
+
* @param this
|
|
165
|
+
* @param methods
|
|
166
|
+
* @param path
|
|
167
|
+
* @param handler
|
|
168
|
+
* @param middlewares
|
|
169
|
+
*/
|
|
170
|
+
static add(methods, path, handler, middlewares) {
|
|
171
|
+
this.ensureState();
|
|
172
|
+
const context = this.groupContext.getStore();
|
|
173
|
+
const activePrefix = context?.prefix ?? this.prefix;
|
|
174
|
+
const activeGroupMiddlewares = context?.groupMiddlewares ?? this.groupMiddlewares;
|
|
175
|
+
methods = Array.isArray(methods) ? methods : [methods];
|
|
176
|
+
middlewares = middlewares ? Array.isArray(middlewares) ? middlewares : [middlewares] : void 0;
|
|
177
|
+
const fullPath = this.normalizePath(`${activePrefix}/${path}`);
|
|
178
|
+
const route = new Route(methods.includes("options") ? methods : methods.concat("options"), fullPath, handler, [
|
|
179
|
+
...this.globalMiddlewares,
|
|
180
|
+
...activeGroupMiddlewares,
|
|
181
|
+
...middlewares || []
|
|
182
|
+
]);
|
|
183
|
+
if (!methods.includes("options") && !this.routesByPathMethod[`OPTIONS ${fullPath}`]) this.options(path, ({ res }) => {
|
|
184
|
+
if (res?.headers?.set) {
|
|
185
|
+
res.headers.set("Allow", "GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD");
|
|
186
|
+
res.status = 204;
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (res?.set) {
|
|
190
|
+
res.set("Allow", "GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD");
|
|
191
|
+
res.sendStatus(204);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
this.routes.push(route);
|
|
195
|
+
for (const method of methods.map((m) => m.toUpperCase())) {
|
|
196
|
+
this.routesByPathMethod[`${method} ${fullPath}`] = route;
|
|
197
|
+
if (!this.routesByMethod[method]) this.routesByMethod[method] = [];
|
|
198
|
+
this.routesByMethod[method].push(route);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Adds a new API resource route to the router for the specified base path and controller, with
|
|
203
|
+
* options to include/exclude specific actions and apply middlewares.
|
|
204
|
+
*
|
|
205
|
+
* @param this
|
|
206
|
+
* @param basePath
|
|
207
|
+
* @param controller
|
|
208
|
+
* @param options
|
|
209
|
+
*/
|
|
210
|
+
static apiResource(basePath, controller, options) {
|
|
211
|
+
const actions = {
|
|
212
|
+
index: {
|
|
213
|
+
method: "get",
|
|
214
|
+
path: "/"
|
|
215
|
+
},
|
|
216
|
+
show: {
|
|
217
|
+
method: "get",
|
|
218
|
+
path: "/:id"
|
|
219
|
+
},
|
|
220
|
+
create: {
|
|
221
|
+
method: "post",
|
|
222
|
+
path: "/"
|
|
223
|
+
},
|
|
224
|
+
update: {
|
|
225
|
+
method: "put",
|
|
226
|
+
path: "/:id"
|
|
227
|
+
},
|
|
228
|
+
destroy: {
|
|
229
|
+
method: "delete",
|
|
230
|
+
path: "/:id"
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
const only = options?.only || Object.keys(actions);
|
|
234
|
+
const except = options?.except || [];
|
|
235
|
+
const preController = typeof controller === "function" ? new controller() : controller;
|
|
236
|
+
for (const action of only) {
|
|
237
|
+
if (except.includes(action)) continue;
|
|
238
|
+
if (typeof preController[action] === "function") {
|
|
239
|
+
const { method, path } = actions[action];
|
|
240
|
+
const actionMiddlewares = typeof options?.middlewares === "object" && !Array.isArray(options.middlewares) ? options.middlewares[action] : options?.middlewares;
|
|
241
|
+
this.add(method, `${basePath}${path}`, [controller, action], Array.isArray(actionMiddlewares) ? actionMiddlewares : actionMiddlewares ? [actionMiddlewares] : void 0);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Adds a new GET route to the router with the specified path, handler, and optional middlewares.
|
|
247
|
+
*
|
|
248
|
+
* @param this The router instance.
|
|
249
|
+
* @param path The path for the GET route.
|
|
250
|
+
* @param handler The handler function for the GET route.
|
|
251
|
+
* @param middlewares Optional middlewares to apply to the GET route.
|
|
252
|
+
*/
|
|
253
|
+
static get(path, handler, middlewares) {
|
|
254
|
+
this.add("get", path, handler, middlewares);
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Adds a new POST route to the router with the specified path, handler, and optional middlewares.
|
|
258
|
+
*
|
|
259
|
+
* @param this
|
|
260
|
+
* @param path
|
|
261
|
+
* @param handler
|
|
262
|
+
* @param middlewares
|
|
263
|
+
*/
|
|
264
|
+
static post(path, handler, middlewares) {
|
|
265
|
+
this.add("post", path, handler, middlewares);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Adds a new PUT route to the router with the specified path, handler, and optional middlewares.
|
|
269
|
+
*
|
|
270
|
+
* @param this
|
|
271
|
+
* @param path
|
|
272
|
+
* @param handler
|
|
273
|
+
* @param middlewares
|
|
274
|
+
*/
|
|
275
|
+
static put(path, handler, middlewares) {
|
|
276
|
+
this.add("put", path, handler, middlewares);
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Adds a new DELETE route to the router with the specified path, handler, and optional middlewares.
|
|
280
|
+
*
|
|
281
|
+
* @param this
|
|
282
|
+
* @param path
|
|
283
|
+
* @param handler
|
|
284
|
+
* @param middlewares
|
|
285
|
+
*/
|
|
286
|
+
static delete(path, handler, middlewares) {
|
|
287
|
+
this.add("delete", path, handler, middlewares);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Adds a new PATCH route to the router with the specified path, handler, and optional middlewares.
|
|
291
|
+
*
|
|
292
|
+
* @param this
|
|
293
|
+
* @param path
|
|
294
|
+
* @param handler
|
|
295
|
+
* @param middlewares
|
|
296
|
+
*/
|
|
297
|
+
static patch(path, handler, middlewares) {
|
|
298
|
+
this.add("patch", path, handler, middlewares);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Adds a new OPTIONS route to the router with the specified path, handler, and optional middlewares.
|
|
302
|
+
*
|
|
303
|
+
* @param this
|
|
304
|
+
* @param path
|
|
305
|
+
* @param handler
|
|
306
|
+
* @param middlewares
|
|
307
|
+
*/
|
|
308
|
+
static options(path, handler, middlewares) {
|
|
309
|
+
this.add("options", path, handler, middlewares);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Adds a new HEAD route to the router with the specified path, handler, and optional middlewares.
|
|
313
|
+
*
|
|
314
|
+
* @param this
|
|
315
|
+
* @param path
|
|
316
|
+
* @param handler
|
|
317
|
+
* @param middlewares
|
|
318
|
+
*/
|
|
319
|
+
static head(path, handler, middlewares) {
|
|
320
|
+
this.add("head", path, handler, middlewares);
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Defines a group of routes with a common prefix and optional middlewares, allowing for better
|
|
324
|
+
* organization and reuse of route configurations.
|
|
325
|
+
*
|
|
326
|
+
* @param this
|
|
327
|
+
* @param prefix
|
|
328
|
+
* @param callback
|
|
329
|
+
* @param middlewares
|
|
330
|
+
*/
|
|
331
|
+
static async group(prefix, callback, middlewares) {
|
|
332
|
+
this.ensureState();
|
|
333
|
+
const context = this.groupContext.getStore();
|
|
334
|
+
const previousPrefix = context?.prefix ?? this.prefix;
|
|
335
|
+
const previousMiddlewares = context?.groupMiddlewares ?? this.groupMiddlewares;
|
|
336
|
+
const fullPrefix = [previousPrefix, prefix].filter(Boolean).join("/");
|
|
337
|
+
const nextContext = {
|
|
338
|
+
prefix: this.normalizePath(fullPrefix),
|
|
339
|
+
groupMiddlewares: [...previousMiddlewares, ...middlewares || []]
|
|
340
|
+
};
|
|
341
|
+
await this.groupContext.run(nextContext, async () => {
|
|
342
|
+
await Promise.resolve(callback());
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Adds global middlewares to the router, which will be applied to all routes.
|
|
347
|
+
*
|
|
348
|
+
* @param this
|
|
349
|
+
* @param middlewares
|
|
350
|
+
* @param callback
|
|
351
|
+
*/
|
|
352
|
+
static middleware(middlewares, callback) {
|
|
353
|
+
this.ensureState();
|
|
354
|
+
const prevMiddlewares = this.globalMiddlewares;
|
|
355
|
+
this.globalMiddlewares = [...prevMiddlewares, ...middlewares || []];
|
|
356
|
+
callback();
|
|
357
|
+
this.globalMiddlewares = prevMiddlewares;
|
|
358
|
+
}
|
|
359
|
+
static allRoutes(type) {
|
|
360
|
+
this.ensureState();
|
|
361
|
+
if (type === "method") return this.routesByMethod;
|
|
362
|
+
if (type === "path") return this.routesByPathMethod;
|
|
363
|
+
return this.routes.filter((e) => e.methods.length > 1 || e.methods[0] !== "options");
|
|
364
|
+
}
|
|
365
|
+
static resolveHandler(route) {
|
|
366
|
+
let handlerFunction;
|
|
367
|
+
let instance = null;
|
|
368
|
+
if (typeof route.handler === "function") handlerFunction = route.handler.bind(route);
|
|
369
|
+
else if (Array.isArray(route.handler) && route.handler.length === 2) {
|
|
370
|
+
const [ControllerType, method] = route.handler;
|
|
371
|
+
if (["function", "object"].includes(typeof ControllerType) && typeof ControllerType[method] === "function") {
|
|
372
|
+
instance = ControllerType;
|
|
373
|
+
handlerFunction = ControllerType[method].bind(ControllerType);
|
|
374
|
+
} else if (typeof ControllerType === "function") {
|
|
375
|
+
instance = new ControllerType();
|
|
376
|
+
if (typeof instance[method] === "function") handlerFunction = instance[method].bind(instance);
|
|
377
|
+
else throw new Error(`Method "${method}" not found in controller instance "${ControllerType.name}"`);
|
|
378
|
+
} else throw new Error(`Invalid controller type for route: ${route.path}`);
|
|
379
|
+
} else throw new Error(`Invalid handler format for route: ${route.path}`);
|
|
380
|
+
return {
|
|
381
|
+
handlerFunction,
|
|
382
|
+
instance
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
static bindRequestToInstance(ctx, instance, route, payload) {
|
|
386
|
+
if (!instance) return;
|
|
387
|
+
instance.ctx = ctx;
|
|
388
|
+
instance.body = payload.body;
|
|
389
|
+
instance.query = payload.query;
|
|
390
|
+
instance.params = payload.params;
|
|
391
|
+
instance.clearRequest = new ClearRequest({
|
|
392
|
+
ctx,
|
|
393
|
+
route,
|
|
394
|
+
body: instance.body,
|
|
395
|
+
query: instance.query,
|
|
396
|
+
params: instance.params
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
//#endregion
|
|
402
|
+
export { ClearRequest, Controller, CoreRouter, Route };
|