@fishka/express 0.9.23 → 0.9.25
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 +227 -106
- package/dist/cjs/auth/auth.utils.d.ts +20 -12
- package/dist/cjs/auth/auth.utils.js +35 -29
- package/dist/cjs/auth/auth.utils.js.map +1 -1
- package/dist/cjs/error-handling.d.ts +21 -0
- package/dist/cjs/error-handling.js +64 -0
- package/dist/cjs/error-handling.js.map +1 -1
- package/dist/cjs/index.d.ts +1 -2
- package/dist/cjs/index.js +1 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/request-utils.d.ts +29 -0
- package/dist/cjs/request-utils.js +115 -0
- package/dist/cjs/request-utils.js.map +1 -0
- package/dist/cjs/thread-local/thread-local-storage-middleware.d.ts +1 -1
- package/dist/cjs/thread-local/thread-local-storage-middleware.js +14 -2
- package/dist/cjs/thread-local/thread-local-storage-middleware.js.map +1 -1
- package/dist/cjs/utils/type-validators.d.ts +1 -1
- package/dist/cjs/utils/type-validators.js +1 -1
- package/dist/cjs/utils/type-validators.js.map +1 -1
- package/dist/esm/auth/auth.utils.d.ts +20 -12
- package/dist/esm/auth/auth.utils.js +35 -29
- package/dist/esm/auth/auth.utils.js.map +1 -1
- package/dist/esm/error-handling.d.ts +21 -0
- package/dist/esm/error-handling.js +63 -0
- package/dist/esm/error-handling.js.map +1 -1
- package/dist/esm/index.d.ts +1 -2
- package/dist/esm/index.js +1 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/request-utils.d.ts +29 -0
- package/dist/esm/request-utils.js +77 -0
- package/dist/esm/request-utils.js.map +1 -0
- package/dist/esm/thread-local/thread-local-storage-middleware.d.ts +1 -1
- package/dist/esm/thread-local/thread-local-storage-middleware.js +15 -3
- package/dist/esm/thread-local/thread-local-storage-middleware.js.map +1 -1
- package/dist/esm/utils/type-validators.d.ts +1 -1
- package/dist/esm/utils/type-validators.js +1 -1
- package/dist/esm/utils/type-validators.js.map +1 -1
- package/package.json +1 -1
- package/dist/cjs/route-table.d.ts +0 -30
- package/dist/cjs/route-table.js +0 -40
- package/dist/cjs/route-table.js.map +0 -1
- package/dist/cjs/router.d.ts +0 -86
- package/dist/cjs/router.js +0 -220
- package/dist/cjs/router.js.map +0 -1
- package/dist/esm/route-table.d.ts +0 -30
- package/dist/esm/route-table.js +0 -36
- package/dist/esm/route-table.js.map +0 -1
- package/dist/esm/router.d.ts +0 -86
- package/dist/esm/router.js +0 -184
- package/dist/esm/router.js.map +0 -1
package/dist/cjs/router.js
DELETED
|
@@ -1,220 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.mount = mount;
|
|
37
|
-
const assertions_1 = require("@fishka/assertions");
|
|
38
|
-
const url = __importStar(require("url"));
|
|
39
|
-
const api_types_1 = require("./api.types");
|
|
40
|
-
const config_1 = require("./config");
|
|
41
|
-
const error_handling_1 = require("./error-handling");
|
|
42
|
-
const http_status_codes_1 = require("./http-status-codes");
|
|
43
|
-
const thread_local_storage_1 = require("./thread-local/thread-local-storage");
|
|
44
|
-
/** Implementation of RequestContext with caching for validated parameters. */
|
|
45
|
-
class RequestContextImpl {
|
|
46
|
-
constructor(
|
|
47
|
-
/** Express request object. */
|
|
48
|
-
req,
|
|
49
|
-
/** Express response object. */
|
|
50
|
-
res,
|
|
51
|
-
/** Authenticated user (if any). */
|
|
52
|
-
authUser,
|
|
53
|
-
/** Request-scoped state storage. */
|
|
54
|
-
state = new Map()) {
|
|
55
|
-
this.req = req;
|
|
56
|
-
this.res = res;
|
|
57
|
-
this.authUser = authUser;
|
|
58
|
-
this.state = state;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Validates a parameter with optional validator and caching.
|
|
62
|
-
* @param name Parameter name.
|
|
63
|
-
* @param rawValue Raw parameter value from request.
|
|
64
|
-
* @param validator Optional validator function.
|
|
65
|
-
* @param isRequired Whether parameter is required (path=true, query=false).
|
|
66
|
-
* @returns Validated value or undefined for optional missing parameters.
|
|
67
|
-
*/
|
|
68
|
-
validateParam(name, rawValue, validator, isRequired) {
|
|
69
|
-
try {
|
|
70
|
-
let result;
|
|
71
|
-
// Check for missing required parameters before calling validator
|
|
72
|
-
if (isRequired && (rawValue === undefined || rawValue === null || rawValue === '')) {
|
|
73
|
-
(0, api_types_1.assertHttp)(false, http_status_codes_1.HTTP_BAD_REQUEST, `Missing required parameter: ${name}`);
|
|
74
|
-
}
|
|
75
|
-
if (validator) {
|
|
76
|
-
// Pass value to validator even if it's undefined/null/empty
|
|
77
|
-
result = validator(rawValue);
|
|
78
|
-
}
|
|
79
|
-
else {
|
|
80
|
-
// Without validator
|
|
81
|
-
if (rawValue === undefined || rawValue === null || rawValue === '') {
|
|
82
|
-
// Already checked for required parameters above
|
|
83
|
-
return undefined;
|
|
84
|
-
}
|
|
85
|
-
result = rawValue;
|
|
86
|
-
}
|
|
87
|
-
return result;
|
|
88
|
-
}
|
|
89
|
-
catch (error) {
|
|
90
|
-
if (error instanceof api_types_1.HttpError)
|
|
91
|
-
throw error;
|
|
92
|
-
throw new api_types_1.HttpError(http_status_codes_1.HTTP_BAD_REQUEST, (0, assertions_1.getMessageFromError)(error));
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
path(name, validator) {
|
|
96
|
-
const rawValue = this.req.params[name];
|
|
97
|
-
const result = this.validateParam(name, rawValue, validator, true);
|
|
98
|
-
(0, api_types_1.assertHttp)(result !== undefined, http_status_codes_1.HTTP_BAD_REQUEST, `Missing required path parameter: ${name}`);
|
|
99
|
-
return result;
|
|
100
|
-
}
|
|
101
|
-
query(name, validator) {
|
|
102
|
-
const parsedUrl = url.parse(this.req.originalUrl, true);
|
|
103
|
-
const rawValue = parsedUrl.query[name];
|
|
104
|
-
const value = Array.isArray(rawValue) ? rawValue[0] : rawValue;
|
|
105
|
-
// Query parameters are always required (like path parameters)
|
|
106
|
-
const result = this.validateParam(name, value, validator, true);
|
|
107
|
-
(0, api_types_1.assertHttp)(result !== undefined, http_status_codes_1.HTTP_BAD_REQUEST, `Missing required query parameter: ${name}`);
|
|
108
|
-
return result;
|
|
109
|
-
}
|
|
110
|
-
body(validator) {
|
|
111
|
-
const apiRequest = this.req.body;
|
|
112
|
-
try {
|
|
113
|
-
// Handle validation based on whether the validator is an object or function
|
|
114
|
-
if (typeof validator === 'function') {
|
|
115
|
-
// It's a ValueAssertion (function) - call it directly
|
|
116
|
-
validator(apiRequest);
|
|
117
|
-
}
|
|
118
|
-
else {
|
|
119
|
-
// It's an ObjectAssertion - use validateObject
|
|
120
|
-
const objectValidator = validator;
|
|
121
|
-
const isEmptyValidator = Object.keys(objectValidator).length === 0;
|
|
122
|
-
const errorMessage = (0, assertions_1.validateObject)(apiRequest, objectValidator, `${http_status_codes_1.HTTP_BAD_REQUEST}: request body`, {
|
|
123
|
-
failOnUnknownFields: !isEmptyValidator,
|
|
124
|
-
});
|
|
125
|
-
(0, api_types_1.assertHttp)(!errorMessage, http_status_codes_1.HTTP_BAD_REQUEST, errorMessage || 'Request body validation failed');
|
|
126
|
-
}
|
|
127
|
-
return apiRequest;
|
|
128
|
-
}
|
|
129
|
-
catch (error) {
|
|
130
|
-
if (error instanceof api_types_1.HttpError)
|
|
131
|
-
throw error;
|
|
132
|
-
throw new api_types_1.HttpError(http_status_codes_1.HTTP_BAD_REQUEST, (0, assertions_1.getMessageFromError)(error));
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
/** Mounts a route with the given method, endpoint, and path. */
|
|
137
|
-
function mount(app, { method, endpoint, path }) {
|
|
138
|
-
const fullPath = path.startsWith('/') ? path : `/${path}`;
|
|
139
|
-
const handler = createRouteHandler(method, endpoint);
|
|
140
|
-
app[method](fullPath, (0, error_handling_1.catchRouteErrors)(handler));
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* @Internal
|
|
144
|
-
* Creates a route handler from an endpoint definition.
|
|
145
|
-
*/
|
|
146
|
-
function createRouteHandler(method, endpoint) {
|
|
147
|
-
return async (req, res, _next) => {
|
|
148
|
-
let result;
|
|
149
|
-
switch (method) {
|
|
150
|
-
case 'post':
|
|
151
|
-
case 'put':
|
|
152
|
-
case 'patch':
|
|
153
|
-
result = await executeBodyEndpoint(endpoint, req, res);
|
|
154
|
-
break;
|
|
155
|
-
case 'delete':
|
|
156
|
-
result = await executeDeleteEndpoint(endpoint, req, res);
|
|
157
|
-
break;
|
|
158
|
-
case 'get':
|
|
159
|
-
result = await executeGetEndpoint(endpoint, req, res);
|
|
160
|
-
break;
|
|
161
|
-
}
|
|
162
|
-
const response = result;
|
|
163
|
-
let status = http_status_codes_1.HTTP_OK;
|
|
164
|
-
let responseToSend = response;
|
|
165
|
-
// Если response - это объект со свойством status, используем его
|
|
166
|
-
if (response && typeof response === 'object' && 'status' in response) {
|
|
167
|
-
const resp = response;
|
|
168
|
-
status = resp.status || http_status_codes_1.HTTP_OK;
|
|
169
|
-
responseToSend = resp;
|
|
170
|
-
}
|
|
171
|
-
// Добавляем requestId в заголовки, если он есть и функция включена
|
|
172
|
-
const tls = (0, thread_local_storage_1.getRequestLocalStorage)();
|
|
173
|
-
const headerName = (0, config_1.getExpressApiConfig)().requestIdHeader;
|
|
174
|
-
if (tls?.requestId && headerName) {
|
|
175
|
-
res.setHeader(headerName, tls.requestId);
|
|
176
|
-
}
|
|
177
|
-
res.status(status);
|
|
178
|
-
res.send(responseToSend);
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* @Internal
|
|
183
|
-
* Runs GET handler with optional middleware.
|
|
184
|
-
*/
|
|
185
|
-
async function executeGetEndpoint(route, req, res) {
|
|
186
|
-
const requestContext = new RequestContextImpl(req, res);
|
|
187
|
-
return await executeWithMiddleware(() => route.run(requestContext), route.middlewares || [], requestContext);
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
|
-
* @Internal
|
|
191
|
-
* Runs DELETE handler with optional middleware.
|
|
192
|
-
*/
|
|
193
|
-
async function executeDeleteEndpoint(route, req, res) {
|
|
194
|
-
const requestContext = new RequestContextImpl(req, res);
|
|
195
|
-
await executeWithMiddleware(() => route.run(requestContext), route.middlewares || [], requestContext);
|
|
196
|
-
return undefined;
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* @Internal
|
|
200
|
-
* Runs POST/PUT/PATCH handler with optional middleware.
|
|
201
|
-
*/
|
|
202
|
-
async function executeBodyEndpoint(route, req, res) {
|
|
203
|
-
const requestContext = new RequestContextImpl(req, res);
|
|
204
|
-
return await executeWithMiddleware(() => route.run(requestContext), route.middlewares || [], requestContext);
|
|
205
|
-
}
|
|
206
|
-
/**
|
|
207
|
-
* @Internal
|
|
208
|
-
* Executes handler with a middleware chain.
|
|
209
|
-
*/
|
|
210
|
-
async function executeWithMiddleware(run, middlewares, context) {
|
|
211
|
-
const current = async (index) => {
|
|
212
|
-
if (index >= middlewares.length) {
|
|
213
|
-
return run();
|
|
214
|
-
}
|
|
215
|
-
const middleware = middlewares[index];
|
|
216
|
-
return (await middleware(() => current(index + 1), context));
|
|
217
|
-
};
|
|
218
|
-
return await current(0);
|
|
219
|
-
}
|
|
220
|
-
//# sourceMappingURL=router.js.map
|
package/dist/cjs/router.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"router.js","sourceRoot":"","sources":["../../src/router.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoMA,sBAIC;AAxMD,mDAAqG;AACrG,yCAA2B;AAC3B,2CAAoE;AAEpE,qCAA+C;AAC/C,qDAAoD;AACpD,2DAAgE;AAChE,8EAA6E;AA2F7E,8EAA8E;AAC9E,MAAM,kBAAkB;IACtB;IACE,8BAA8B;IACd,GAAmB;IACnC,+BAA+B;IACf,GAAoB;IACpC,mCAAmC;IAC5B,QAAmB;IAC1B,oCAAoC;IACpB,QAA8B,IAAI,GAAG,EAAE;QANvC,QAAG,GAAH,GAAG,CAAgB;QAEnB,QAAG,GAAH,GAAG,CAAiB;QAE7B,aAAQ,GAAR,QAAQ,CAAW;QAEV,UAAK,GAAL,KAAK,CAAkC;IACtD,CAAC;IAEJ;;;;;;;OAOG;IACK,aAAa,CACnB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,qBAAqB,CACzB,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,EAC/B,KAAK,CAAC,WAAW,IAAI,EAAE,EACvB,cAAc,CACf,CAAC;IACF,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;GAGG;AACH,KAAK,UAAU,mBAAmB,CAChC,KAA6G,EAC7G,GAAmB,EACnB,GAAoB;IAEpB,MAAM,cAAc,GAAG,IAAI,kBAAkB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACxD,OAAO,MAAM,qBAAqB,CAChC,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,EAC/B,KAAK,CAAC,WAAW,IAAI,EAAE,EACvB,cAAc,CACf,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,KAAK,UAAU,qBAAqB,CAClC,GAAmC,EACnC,WAA+C,EAC/C,OAAgB;IAEhB,MAAM,OAAO,GAAG,KAAK,EAAE,KAAa,EAAmB,EAAE;QACvD,IAAI,KAAK,IAAI,WAAW,CAAC,MAAM,EAAE,CAAC;YAChC,OAAO,GAAG,EAAE,CAAC;QACf,CAAC;QACD,MAAM,UAAU,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,CAAC,MAAM,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAW,CAAC;IACzE,CAAC,CAAC;IACF,OAAO,MAAM,OAAO,CAAC,CAAC,CAAC,CAAC;AAC1B,CAAC"}
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { DeleteEndpoint, GetEndpoint, PatchEndpoint, PostEndpoint, PutEndpoint, RequestContext } from './router';
|
|
2
|
-
import { ExpressRouter } from './utils/express.utils';
|
|
3
|
-
/**
|
|
4
|
-
* Helper utility for organizing and mounting routes.
|
|
5
|
-
* Provides a fluent interface for registering multiple handlers.
|
|
6
|
-
*/
|
|
7
|
-
export declare class RouteTable {
|
|
8
|
-
private readonly app;
|
|
9
|
-
constructor(app: ExpressRouter);
|
|
10
|
-
/** Register a GET endpoint. */
|
|
11
|
-
get<Result>(path: string, endpoint: GetEndpoint<Result>): this;
|
|
12
|
-
/** Register a GET endpoint with function shorthand. */
|
|
13
|
-
get<Result>(path: string, run: (ctx: RequestContext) => Result | Promise<Result>): this;
|
|
14
|
-
/** Register a POST endpoint. */
|
|
15
|
-
post<Result = void>(path: string, endpoint: PostEndpoint<Result>): this;
|
|
16
|
-
/** Register a POST endpoint with function shorthand. */
|
|
17
|
-
post<Result = void>(path: string, run: (ctx: RequestContext) => Result | Promise<Result>): this;
|
|
18
|
-
/** Register a PATCH endpoint. */
|
|
19
|
-
patch<Result = void>(path: string, endpoint: PatchEndpoint<Result>): this;
|
|
20
|
-
/** Register a PATCH endpoint with function shorthand. */
|
|
21
|
-
patch<Result = void>(path: string, run: (ctx: RequestContext) => Result | Promise<Result>): this;
|
|
22
|
-
/** Register a PUT endpoint. */
|
|
23
|
-
put<Result = void>(path: string, endpoint: PutEndpoint<Result>): this;
|
|
24
|
-
/** Register a PUT endpoint with function shorthand. */
|
|
25
|
-
put<Result = void>(path: string, run: (ctx: RequestContext) => Result | Promise<Result>): this;
|
|
26
|
-
/** Register a DELETE endpoint with a full endpoint object. */
|
|
27
|
-
delete(path: string, endpoint: DeleteEndpoint): this;
|
|
28
|
-
/** Register a DELETE endpoint with function shorthand. */
|
|
29
|
-
delete(path: string, run: (ctx: RequestContext) => void | Promise<void>): this;
|
|
30
|
-
}
|
package/dist/esm/route-table.js
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { mount } from './router';
|
|
2
|
-
/**
|
|
3
|
-
* Helper utility for organizing and mounting routes.
|
|
4
|
-
* Provides a fluent interface for registering multiple handlers.
|
|
5
|
-
*/
|
|
6
|
-
export class RouteTable {
|
|
7
|
-
constructor(app) {
|
|
8
|
-
this.app = app;
|
|
9
|
-
}
|
|
10
|
-
get(path, endpointOrRun) {
|
|
11
|
-
const endpoint = typeof endpointOrRun === 'function' ? { run: endpointOrRun } : endpointOrRun;
|
|
12
|
-
mount(this.app, { method: 'get', endpoint: endpoint, path });
|
|
13
|
-
return this;
|
|
14
|
-
}
|
|
15
|
-
post(path, endpointOrRun) {
|
|
16
|
-
const endpoint = typeof endpointOrRun === 'function' ? { run: endpointOrRun } : endpointOrRun;
|
|
17
|
-
mount(this.app, { method: 'post', endpoint: endpoint, path });
|
|
18
|
-
return this;
|
|
19
|
-
}
|
|
20
|
-
patch(path, endpointOrRun) {
|
|
21
|
-
const endpoint = typeof endpointOrRun === 'function' ? { run: endpointOrRun } : endpointOrRun;
|
|
22
|
-
mount(this.app, { method: 'patch', endpoint: endpoint, path });
|
|
23
|
-
return this;
|
|
24
|
-
}
|
|
25
|
-
put(path, endpointOrRun) {
|
|
26
|
-
const endpoint = typeof endpointOrRun === 'function' ? { run: endpointOrRun } : endpointOrRun;
|
|
27
|
-
mount(this.app, { method: 'put', endpoint: endpoint, path });
|
|
28
|
-
return this;
|
|
29
|
-
}
|
|
30
|
-
delete(path, endpointOrRun) {
|
|
31
|
-
const endpoint = typeof endpointOrRun === 'function' ? { run: endpointOrRun } : endpointOrRun;
|
|
32
|
-
mount(this.app, { method: 'delete', endpoint: endpoint, path });
|
|
33
|
-
return this;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
//# sourceMappingURL=route-table.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"route-table.js","sourceRoot":"","sources":["../../src/route-table.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,EAA4D,MAAM,UAAU,CAAC;AAGxH;;;GAGG;AACH,MAAM,OAAO,UAAU;IACrB,YAA6B,GAAkB;QAAlB,QAAG,GAAH,GAAG,CAAe;IAAG,CAAC;IAQnD,GAAG,CACD,IAAY,EACZ,aAAwF;QAExF,MAAM,QAAQ,GAAG,OAAO,aAAa,KAAK,UAAU,CAAC,CAAC,CAAC,E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AAM,QAAQ,GAAG,OAAO,aAAa,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC;QAC9F,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAA0B,EAAE,IAAI,EAAE,CAAC,CAAC;QAClF,OAAO,IAAI,CAAC;IACd,CAAC;CACF"}
|
package/dist/esm/router.d.ts
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { Assertion } from '@fishka/assertions';
|
|
2
|
-
import { ParamValidator } from './api.types';
|
|
3
|
-
import { AuthUser } from './auth/auth.types';
|
|
4
|
-
import { ExpressRequest, ExpressResponse, ExpressRouter } from './utils/express.utils';
|
|
5
|
-
/**
|
|
6
|
-
* Generic middleware hook for endpoint execution.
|
|
7
|
-
* Allows custom logic like transaction management, authorization checks, etc.
|
|
8
|
-
*/
|
|
9
|
-
export type EndpointMiddleware<Context = RequestContext> = (run: () => Promise<unknown>, context: Context) => Promise<unknown>;
|
|
10
|
-
/** Generic request context passed to all handlers. Database-agnostic and extensible. */
|
|
11
|
-
export interface RequestContext {
|
|
12
|
-
/** Express Request object. */
|
|
13
|
-
req: ExpressRequest;
|
|
14
|
-
/** Express Response object. */
|
|
15
|
-
res: ExpressResponse;
|
|
16
|
-
/** Authenticated user (if any). Populated by auth middleware. */
|
|
17
|
-
authUser?: AuthUser;
|
|
18
|
-
/**
|
|
19
|
-
* Get and validate a path parameter.
|
|
20
|
-
* @param name - Name of the path parameter
|
|
21
|
-
* @param validator - Optional validator. If not provided, returns the raw string value.
|
|
22
|
-
* @returns Validated value of type T (or string if no validator)
|
|
23
|
-
* @throws {HttpError} 400 Bad Request if validation fails
|
|
24
|
-
*/
|
|
25
|
-
path<T = string>(name: string, validator?: ParamValidator<T>): T;
|
|
26
|
-
/**
|
|
27
|
-
* Get and validate a query parameter.
|
|
28
|
-
* @param name - Name of the query parameter
|
|
29
|
-
* @param validator - Optional validator. If not provided, returns the raw string value or undefined.
|
|
30
|
-
* @returns Validated value of type T.
|
|
31
|
-
* @throws {HttpError} 400 Bad Request if validation fails
|
|
32
|
-
*/
|
|
33
|
-
query<T = string>(name: string, validator?: ParamValidator<T>): T;
|
|
34
|
-
/**
|
|
35
|
-
* Get and validate the request body.
|
|
36
|
-
* @param validator - Validator function or object assertion
|
|
37
|
-
* @returns Validated body of type T
|
|
38
|
-
* @throws {HttpError} 400 Bad Request if validation fails
|
|
39
|
-
*/
|
|
40
|
-
body<T>(validator: Assertion<T>): T;
|
|
41
|
-
/**
|
|
42
|
-
* Generic state storage for middleware to attach data.
|
|
43
|
-
* Allows middleware to pass information to handlers and other middleware.
|
|
44
|
-
*/
|
|
45
|
-
state: Map<string, unknown>;
|
|
46
|
-
}
|
|
47
|
-
/** Base interface with common endpoint properties. */
|
|
48
|
-
export interface EndpointBase<Result = unknown> {
|
|
49
|
-
/** Optional middleware to execute before the handler. */
|
|
50
|
-
middlewares?: Array<EndpointMiddleware>;
|
|
51
|
-
/** Handler function. Can be sync or async. */
|
|
52
|
-
run: (ctx: RequestContext) => Result | Promise<Result>;
|
|
53
|
-
}
|
|
54
|
-
/** Descriptor for GET list routes. */
|
|
55
|
-
export type GetListEndpoint<ResultElementType> = EndpointBase<Array<ResultElementType>>;
|
|
56
|
-
/** Descriptor for GET routes. */
|
|
57
|
-
export type GetEndpoint<Result> = EndpointBase<Result>;
|
|
58
|
-
/** Descriptor for POST routes. */
|
|
59
|
-
export type PostEndpoint<Result = void> = EndpointBase<Result>;
|
|
60
|
-
/** Same as POST. Used for full object updates. */
|
|
61
|
-
export type PutEndpoint<Result = void> = EndpointBase<Result>;
|
|
62
|
-
/** Same as PUT. While PUT is used for the whole object update, PATCH is used for a partial update. */
|
|
63
|
-
export type PatchEndpoint<Result = void> = EndpointBase<Result>;
|
|
64
|
-
/** Descriptor for DELETE routes. */
|
|
65
|
-
export type DeleteEndpoint = EndpointBase<void>;
|
|
66
|
-
/** Union type for all route registration info objects. */
|
|
67
|
-
export type RouteRegistrationInfo = ({
|
|
68
|
-
method: 'get';
|
|
69
|
-
endpoint: GetEndpoint<unknown> | GetListEndpoint<unknown>;
|
|
70
|
-
} | {
|
|
71
|
-
method: 'post';
|
|
72
|
-
endpoint: PostEndpoint<unknown>;
|
|
73
|
-
} | {
|
|
74
|
-
method: 'patch';
|
|
75
|
-
endpoint: PatchEndpoint<unknown>;
|
|
76
|
-
} | {
|
|
77
|
-
method: 'put';
|
|
78
|
-
endpoint: PutEndpoint<unknown>;
|
|
79
|
-
} | {
|
|
80
|
-
method: 'delete';
|
|
81
|
-
endpoint: DeleteEndpoint;
|
|
82
|
-
}) & {
|
|
83
|
-
path: string;
|
|
84
|
-
};
|
|
85
|
-
/** Mounts a route with the given method, endpoint, and path. */
|
|
86
|
-
export declare function mount(app: ExpressRouter, { method, endpoint, path }: RouteRegistrationInfo): void;
|
package/dist/esm/router.js
DELETED
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
import { getMessageFromError, validateObject } from '@fishka/assertions';
|
|
2
|
-
import * as url from 'url';
|
|
3
|
-
import { assertHttp, HttpError } from './api.types';
|
|
4
|
-
import { getExpressApiConfig } from './config';
|
|
5
|
-
import { catchRouteErrors } from './error-handling';
|
|
6
|
-
import { HTTP_BAD_REQUEST, HTTP_OK } from './http-status-codes';
|
|
7
|
-
import { getRequestLocalStorage } from './thread-local/thread-local-storage';
|
|
8
|
-
/** Implementation of RequestContext with caching for validated parameters. */
|
|
9
|
-
class RequestContextImpl {
|
|
10
|
-
constructor(
|
|
11
|
-
/** Express request object. */
|
|
12
|
-
req,
|
|
13
|
-
/** Express response object. */
|
|
14
|
-
res,
|
|
15
|
-
/** Authenticated user (if any). */
|
|
16
|
-
authUser,
|
|
17
|
-
/** Request-scoped state storage. */
|
|
18
|
-
state = new Map()) {
|
|
19
|
-
this.req = req;
|
|
20
|
-
this.res = res;
|
|
21
|
-
this.authUser = authUser;
|
|
22
|
-
this.state = state;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Validates a parameter with optional validator and caching.
|
|
26
|
-
* @param name Parameter name.
|
|
27
|
-
* @param rawValue Raw parameter value from request.
|
|
28
|
-
* @param validator Optional validator function.
|
|
29
|
-
* @param isRequired Whether parameter is required (path=true, query=false).
|
|
30
|
-
* @returns Validated value or undefined for optional missing parameters.
|
|
31
|
-
*/
|
|
32
|
-
validateParam(name, rawValue, validator, isRequired) {
|
|
33
|
-
try {
|
|
34
|
-
let result;
|
|
35
|
-
// Check for missing required parameters before calling validator
|
|
36
|
-
if (isRequired && (rawValue === undefined || rawValue === null || rawValue === '')) {
|
|
37
|
-
assertHttp(false, HTTP_BAD_REQUEST, `Missing required parameter: ${name}`);
|
|
38
|
-
}
|
|
39
|
-
if (validator) {
|
|
40
|
-
// Pass value to validator even if it's undefined/null/empty
|
|
41
|
-
result = validator(rawValue);
|
|
42
|
-
}
|
|
43
|
-
else {
|
|
44
|
-
// Without validator
|
|
45
|
-
if (rawValue === undefined || rawValue === null || rawValue === '') {
|
|
46
|
-
// Already checked for required parameters above
|
|
47
|
-
return undefined;
|
|
48
|
-
}
|
|
49
|
-
result = rawValue;
|
|
50
|
-
}
|
|
51
|
-
return result;
|
|
52
|
-
}
|
|
53
|
-
catch (error) {
|
|
54
|
-
if (error instanceof HttpError)
|
|
55
|
-
throw error;
|
|
56
|
-
throw new HttpError(HTTP_BAD_REQUEST, getMessageFromError(error));
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
path(name, validator) {
|
|
60
|
-
const rawValue = this.req.params[name];
|
|
61
|
-
const result = this.validateParam(name, rawValue, validator, true);
|
|
62
|
-
assertHttp(result !== undefined, HTTP_BAD_REQUEST, `Missing required path parameter: ${name}`);
|
|
63
|
-
return result;
|
|
64
|
-
}
|
|
65
|
-
query(name, validator) {
|
|
66
|
-
const parsedUrl = url.parse(this.req.originalUrl, true);
|
|
67
|
-
const rawValue = parsedUrl.query[name];
|
|
68
|
-
const value = Array.isArray(rawValue) ? rawValue[0] : rawValue;
|
|
69
|
-
// Query parameters are always required (like path parameters)
|
|
70
|
-
const result = this.validateParam(name, value, validator, true);
|
|
71
|
-
assertHttp(result !== undefined, HTTP_BAD_REQUEST, `Missing required query parameter: ${name}`);
|
|
72
|
-
return result;
|
|
73
|
-
}
|
|
74
|
-
body(validator) {
|
|
75
|
-
const apiRequest = this.req.body;
|
|
76
|
-
try {
|
|
77
|
-
// Handle validation based on whether the validator is an object or function
|
|
78
|
-
if (typeof validator === 'function') {
|
|
79
|
-
// It's a ValueAssertion (function) - call it directly
|
|
80
|
-
validator(apiRequest);
|
|
81
|
-
}
|
|
82
|
-
else {
|
|
83
|
-
// It's an ObjectAssertion - use validateObject
|
|
84
|
-
const objectValidator = validator;
|
|
85
|
-
const isEmptyValidator = Object.keys(objectValidator).length === 0;
|
|
86
|
-
const errorMessage = validateObject(apiRequest, objectValidator, `${HTTP_BAD_REQUEST}: request body`, {
|
|
87
|
-
failOnUnknownFields: !isEmptyValidator,
|
|
88
|
-
});
|
|
89
|
-
assertHttp(!errorMessage, HTTP_BAD_REQUEST, errorMessage || 'Request body validation failed');
|
|
90
|
-
}
|
|
91
|
-
return apiRequest;
|
|
92
|
-
}
|
|
93
|
-
catch (error) {
|
|
94
|
-
if (error instanceof HttpError)
|
|
95
|
-
throw error;
|
|
96
|
-
throw new HttpError(HTTP_BAD_REQUEST, getMessageFromError(error));
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
/** Mounts a route with the given method, endpoint, and path. */
|
|
101
|
-
export function mount(app, { method, endpoint, path }) {
|
|
102
|
-
const fullPath = path.startsWith('/') ? path : `/${path}`;
|
|
103
|
-
const handler = createRouteHandler(method, endpoint);
|
|
104
|
-
app[method](fullPath, catchRouteErrors(handler));
|
|
105
|
-
}
|
|
106
|
-
/**
|
|
107
|
-
* @Internal
|
|
108
|
-
* Creates a route handler from an endpoint definition.
|
|
109
|
-
*/
|
|
110
|
-
function createRouteHandler(method, endpoint) {
|
|
111
|
-
return async (req, res, _next) => {
|
|
112
|
-
let result;
|
|
113
|
-
switch (method) {
|
|
114
|
-
case 'post':
|
|
115
|
-
case 'put':
|
|
116
|
-
case 'patch':
|
|
117
|
-
result = await executeBodyEndpoint(endpoint, req, res);
|
|
118
|
-
break;
|
|
119
|
-
case 'delete':
|
|
120
|
-
result = await executeDeleteEndpoint(endpoint, req, res);
|
|
121
|
-
break;
|
|
122
|
-
case 'get':
|
|
123
|
-
result = await executeGetEndpoint(endpoint, req, res);
|
|
124
|
-
break;
|
|
125
|
-
}
|
|
126
|
-
const response = result;
|
|
127
|
-
let status = HTTP_OK;
|
|
128
|
-
let responseToSend = response;
|
|
129
|
-
// Если response - это объект со свойством status, используем его
|
|
130
|
-
if (response && typeof response === 'object' && 'status' in response) {
|
|
131
|
-
const resp = response;
|
|
132
|
-
status = resp.status || HTTP_OK;
|
|
133
|
-
responseToSend = resp;
|
|
134
|
-
}
|
|
135
|
-
// Добавляем requestId в заголовки, если он есть и функция включена
|
|
136
|
-
const tls = getRequestLocalStorage();
|
|
137
|
-
const headerName = getExpressApiConfig().requestIdHeader;
|
|
138
|
-
if (tls?.requestId && headerName) {
|
|
139
|
-
res.setHeader(headerName, tls.requestId);
|
|
140
|
-
}
|
|
141
|
-
res.status(status);
|
|
142
|
-
res.send(responseToSend);
|
|
143
|
-
};
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* @Internal
|
|
147
|
-
* Runs GET handler with optional middleware.
|
|
148
|
-
*/
|
|
149
|
-
async function executeGetEndpoint(route, req, res) {
|
|
150
|
-
const requestContext = new RequestContextImpl(req, res);
|
|
151
|
-
return await executeWithMiddleware(() => route.run(requestContext), route.middlewares || [], requestContext);
|
|
152
|
-
}
|
|
153
|
-
/**
|
|
154
|
-
* @Internal
|
|
155
|
-
* Runs DELETE handler with optional middleware.
|
|
156
|
-
*/
|
|
157
|
-
async function executeDeleteEndpoint(route, req, res) {
|
|
158
|
-
const requestContext = new RequestContextImpl(req, res);
|
|
159
|
-
await executeWithMiddleware(() => route.run(requestContext), route.middlewares || [], requestContext);
|
|
160
|
-
return undefined;
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* @Internal
|
|
164
|
-
* Runs POST/PUT/PATCH handler with optional middleware.
|
|
165
|
-
*/
|
|
166
|
-
async function executeBodyEndpoint(route, req, res) {
|
|
167
|
-
const requestContext = new RequestContextImpl(req, res);
|
|
168
|
-
return await executeWithMiddleware(() => route.run(requestContext), route.middlewares || [], requestContext);
|
|
169
|
-
}
|
|
170
|
-
/**
|
|
171
|
-
* @Internal
|
|
172
|
-
* Executes handler with a middleware chain.
|
|
173
|
-
*/
|
|
174
|
-
async function executeWithMiddleware(run, middlewares, context) {
|
|
175
|
-
const current = async (index) => {
|
|
176
|
-
if (index >= middlewares.length) {
|
|
177
|
-
return run();
|
|
178
|
-
}
|
|
179
|
-
const middleware = middlewares[index];
|
|
180
|
-
return (await middleware(() => current(index + 1), context));
|
|
181
|
-
};
|
|
182
|
-
return await current(0);
|
|
183
|
-
}
|
|
184
|
-
//# sourceMappingURL=router.js.map
|
package/dist/esm/router.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"router.js","sourceRoot":"","sources":["../../src/router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,mBAAmB,EAAmB,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACrG,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,SAAS,EAAkB,MAAM,aAAa,CAAC;AAEpE,OAAO,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAChE,OAAO,EAAE,sBAAsB,EAAE,MAAM,qCAAq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