@fishka/express 0.9.5 → 0.9.7
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/dist/cjs/api.types.d.ts +83 -0
- package/dist/cjs/api.types.js +38 -2
- package/dist/cjs/auth/auth-strategy.d.ts +42 -0
- package/dist/cjs/auth/auth-strategy.js +2 -2
- package/dist/cjs/auth/auth.types.d.ts +42 -0
- package/dist/cjs/auth/auth.utils.d.ts +31 -0
- package/dist/cjs/auth/auth.utils.js +3 -3
- package/dist/cjs/auth/bearer-auth-strategy.d.ts +38 -0
- package/dist/cjs/auth/bearer-auth-strategy.js +2 -2
- package/dist/cjs/config.d.ts +23 -0
- package/dist/cjs/error-handling.d.ts +9 -0
- package/dist/cjs/error-handling.js +4 -4
- package/dist/cjs/http-status-codes.d.ts +179 -0
- package/dist/cjs/http-status-codes.js +228 -0
- package/dist/cjs/index.d.ts +15 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/rate-limit/in-memory-rate-limiter.d.ts +35 -0
- package/dist/cjs/rate-limit/rate-limit.d.ts +19 -0
- package/dist/cjs/rate-limit/rate-limit.types.d.ts +23 -0
- package/dist/cjs/route-table.d.ts +23 -0
- package/dist/cjs/router.d.ts +110 -0
- package/dist/cjs/router.js +11 -11
- package/dist/cjs/thread-local/thread-local-storage-middleware.d.ts +9 -0
- package/dist/cjs/thread-local/thread-local-storage.d.ts +25 -0
- package/dist/cjs/utils/conversion.utils.d.ts +14 -0
- package/dist/cjs/utils/express.utils.d.ts +7 -0
- package/dist/esm/api.types.d.ts +83 -0
- package/dist/esm/api.types.js +37 -2
- package/dist/esm/auth/auth-strategy.d.ts +42 -0
- package/dist/esm/auth/auth-strategy.js +2 -2
- package/dist/esm/auth/auth.types.d.ts +42 -0
- package/dist/esm/auth/auth.utils.d.ts +31 -0
- package/dist/esm/auth/auth.utils.js +3 -3
- package/dist/esm/auth/bearer-auth-strategy.d.ts +38 -0
- package/dist/esm/auth/bearer-auth-strategy.js +2 -2
- package/dist/esm/config.d.ts +23 -0
- package/dist/esm/error-handling.d.ts +9 -0
- package/dist/esm/error-handling.js +4 -4
- package/dist/esm/http-status-codes.d.ts +179 -0
- package/dist/esm/http-status-codes.js +224 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/rate-limit/in-memory-rate-limiter.d.ts +35 -0
- package/dist/esm/rate-limit/rate-limit.d.ts +19 -0
- package/dist/esm/rate-limit/rate-limit.types.d.ts +23 -0
- package/dist/esm/route-table.d.ts +23 -0
- package/dist/esm/router.d.ts +110 -0
- package/dist/esm/router.js +12 -12
- package/dist/esm/thread-local/thread-local-storage-middleware.d.ts +9 -0
- package/dist/esm/thread-local/thread-local-storage.d.ts +25 -0
- package/dist/esm/utils/conversion.utils.d.ts +14 -0
- package/dist/esm/utils/express.utils.d.ts +7 -0
- package/package.json +1 -1
- package/dist/cjs/http.types.js +0 -38
- package/dist/esm/http.types.js +0 -35
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/** The request has succeeded (200) */
|
|
2
|
+
export const HTTP_OK = 200;
|
|
3
|
+
/** The request has been fulfilled, and a new resource is created (201) */
|
|
4
|
+
export const HTTP_CREATED = 201;
|
|
5
|
+
/** The request has been accepted for processing, but the processing is not yet complete (202) */
|
|
6
|
+
export const HTTP_ACCEPTED = 202;
|
|
7
|
+
/** The server successfully processed the request, and is not returning any content (204) */
|
|
8
|
+
export const HTTP_NO_CONTENT = 204;
|
|
9
|
+
/** The request has been successfully processed, but is returning no content (205) */
|
|
10
|
+
export const HTTP_RESET_CONTENT = 205;
|
|
11
|
+
/** The server is delivering only part of the resource due to a range header sent by the client (206) */
|
|
12
|
+
export const HTTP_PARTIAL_CONTENT = 206;
|
|
13
|
+
/** The IM used the server processed a request successfully, but the response is transformed (226) */
|
|
14
|
+
export const HTTP_IM_USED = 226;
|
|
15
|
+
/** The resource has been moved permanently to a new URL (301) */
|
|
16
|
+
export const HTTP_MOVED_PERMANENTLY = 301;
|
|
17
|
+
/** The resource is available at a different URL (302) */
|
|
18
|
+
export const HTTP_FOUND = 302;
|
|
19
|
+
/** The resource has not been modified since the last request (304) */
|
|
20
|
+
export const HTTP_NOT_MODIFIED = 304;
|
|
21
|
+
/** The server could not understand the request due to invalid syntax (400) */
|
|
22
|
+
export const HTTP_BAD_REQUEST = 400;
|
|
23
|
+
/** The client must authenticate itself to get the requested response (401) */
|
|
24
|
+
export const HTTP_UNAUTHORIZED = 401;
|
|
25
|
+
/** The client does not have access rights to the content (403) */
|
|
26
|
+
export const HTTP_FORBIDDEN = 403;
|
|
27
|
+
/** The server cannot find the requested resource (404) */
|
|
28
|
+
export const HTTP_NOT_FOUND = 404;
|
|
29
|
+
/** The request method is known by the server but is not supported by the target resource (405) */
|
|
30
|
+
export const HTTP_METHOD_NOT_ALLOWED = 405;
|
|
31
|
+
/** The client must authenticate using a proxy (407) */
|
|
32
|
+
export const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
|
|
33
|
+
/** The server timed out waiting for the request (408) */
|
|
34
|
+
export const HTTP_REQUEST_TIMEOUT = 408;
|
|
35
|
+
/** The request conflicts with the current state of the server (409) */
|
|
36
|
+
export const HTTP_CONFLICT = 409;
|
|
37
|
+
/** The resource requested is no longer available and will not be available again (410) */
|
|
38
|
+
export const HTTP_GONE = 410;
|
|
39
|
+
/** The request does not meet the preconditions that the server requires (412) */
|
|
40
|
+
export const HTTP_PRECONDITION_FAILED = 412;
|
|
41
|
+
/** The client sent a request that is too large for the server to process (413) */
|
|
42
|
+
export const HTTP_PAYLOAD_TOO_LARGE = 413;
|
|
43
|
+
/** The URI requested by the client is too long for the server to process (414) */
|
|
44
|
+
export const HTTP_URI_TOO_LONG = 414;
|
|
45
|
+
/** The media format of the requested data is not supported by the server (415) */
|
|
46
|
+
export const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
|
|
47
|
+
/** The range specified by the client cannot be fulfilled (416) */
|
|
48
|
+
export const HTTP_RANGE_NOT_SATISFIABLE = 416;
|
|
49
|
+
/** The expectation given in the request header could not be met by the server (417) */
|
|
50
|
+
export const HTTP_EXPECTATION_FAILED = 417;
|
|
51
|
+
/** The server refuses to brew coffee because it is a teapot (418) - an Easter egg from RFC 2324 */
|
|
52
|
+
export const HTTP_IM_A_TEAPOT = 418;
|
|
53
|
+
/** The request was well-formed but was unable to be followed due to semantic errors (422) */
|
|
54
|
+
export const HTTP_UNPROCESSABLE_ENTITY = 422;
|
|
55
|
+
/** The resource that is being accessed is locked (423) */
|
|
56
|
+
export const HTTP_LOCKED = 423;
|
|
57
|
+
/** The resource requested is dependent on another resource that has failed (424) */
|
|
58
|
+
export const HTTP_FAILED_DEPENDENCY = 424;
|
|
59
|
+
/** The server is unwilling to risk processing a request that might be replayed (425) */
|
|
60
|
+
export const HTTP_TOO_EARLY = 425;
|
|
61
|
+
/** The client needs to upgrade its protocol (426) */
|
|
62
|
+
export const HTTP_UPGRADE_REQUIRED = 426;
|
|
63
|
+
/** The server requires the request to be conditional (428) */
|
|
64
|
+
export const HTTP_PRECONDITION_REQUIRED = 428;
|
|
65
|
+
/** The client has sent too many requests in a given amount of time (429) */
|
|
66
|
+
export const HTTP_TOO_MANY_REQUESTS = 429;
|
|
67
|
+
/** The request header fields are too large (431) */
|
|
68
|
+
export const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
|
|
69
|
+
/** The client closed the connection with the server before the request was completed (444) */
|
|
70
|
+
export const HTTP_CONNECTION_CLOSED_WITHOUT_RESPONSE = 444;
|
|
71
|
+
/** The client requested an unavailable legal action (451) */
|
|
72
|
+
export const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
|
|
73
|
+
/** The server encountered an internal error and was unable to complete the request (500) */
|
|
74
|
+
export const HTTP_INTERNAL_SERVER_ERROR = 500;
|
|
75
|
+
/** The request method is not supported by the server and cannot be handled (501) */
|
|
76
|
+
export const HTTP_NOT_IMPLEMENTED = 501;
|
|
77
|
+
/** The server, while acting as a gateway or proxy, received an invalid response from the upstream server (502) */
|
|
78
|
+
export const HTTP_BAD_GATEWAY = 502;
|
|
79
|
+
/** The server is not ready to handle the request, typically due to temporary overload or maintenance (503) */
|
|
80
|
+
export const HTTP_SERVICE_UNAVAILABLE = 503;
|
|
81
|
+
/** The server, while acting as a gateway or proxy, did not get a response in time from the upstream server (504) */
|
|
82
|
+
export const HTTP_GATEWAY_TIMEOUT = 504;
|
|
83
|
+
/**
|
|
84
|
+
* An object containing common HTTP status codes.
|
|
85
|
+
* These constants can be used to improve code readability and maintainability.
|
|
86
|
+
* @deprecated Use individual HTTP_* constants for better tree-shaking
|
|
87
|
+
*/
|
|
88
|
+
export const HttpStatusCode = {
|
|
89
|
+
/** The request has succeeded (200) */
|
|
90
|
+
OK: HTTP_OK,
|
|
91
|
+
/** The request has been fulfilled, and a new resource is created (201) */
|
|
92
|
+
CREATED: HTTP_CREATED,
|
|
93
|
+
/** The request has been accepted for processing, but the processing is not yet complete (202) */
|
|
94
|
+
ACCEPTED: HTTP_ACCEPTED,
|
|
95
|
+
/** The server successfully processed the request, and is not returning any content (204) */
|
|
96
|
+
NO_CONTENT: HTTP_NO_CONTENT,
|
|
97
|
+
/** The request has been successfully processed, but is returning no content (205) */
|
|
98
|
+
RESET_CONTENT: HTTP_RESET_CONTENT,
|
|
99
|
+
/** The server is delivering only part of the resource due to a range header sent by the client (206) */
|
|
100
|
+
PARTIAL_CONTENT: HTTP_PARTIAL_CONTENT,
|
|
101
|
+
/** The IM used the server processed a request successfully, but the response is transformed (226) */
|
|
102
|
+
IM_USED: HTTP_IM_USED,
|
|
103
|
+
/** The resource has been moved permanently to a new URL (301) */
|
|
104
|
+
MOVED_PERMANENTLY: HTTP_MOVED_PERMANENTLY,
|
|
105
|
+
/** The resource is available at a different URL (302) */
|
|
106
|
+
FOUND: HTTP_FOUND,
|
|
107
|
+
/** The resource has not been modified since the last request (304) */
|
|
108
|
+
NOT_MODIFIED: HTTP_NOT_MODIFIED,
|
|
109
|
+
/** The server could not understand the request due to invalid syntax (400) */
|
|
110
|
+
BAD_REQUEST: HTTP_BAD_REQUEST,
|
|
111
|
+
/** The client must authenticate itself to get the requested response (401) */
|
|
112
|
+
UNAUTHORIZED: HTTP_UNAUTHORIZED,
|
|
113
|
+
/** The client does not have access rights to the content (403) */
|
|
114
|
+
FORBIDDEN: HTTP_FORBIDDEN,
|
|
115
|
+
/** The server cannot find the requested resource (404) */
|
|
116
|
+
NOT_FOUND: HTTP_NOT_FOUND,
|
|
117
|
+
/** The request method is known by the server but is not supported by the target resource (405) */
|
|
118
|
+
METHOD_NOT_ALLOWED: HTTP_METHOD_NOT_ALLOWED,
|
|
119
|
+
/** The client must authenticate using a proxy (407) */
|
|
120
|
+
PROXY_AUTHENTICATION_REQUIRED: HTTP_PROXY_AUTHENTICATION_REQUIRED,
|
|
121
|
+
/** The server timed out waiting for the request (408) */
|
|
122
|
+
REQUEST_TIMEOUT: HTTP_REQUEST_TIMEOUT,
|
|
123
|
+
/** The request conflicts with the current state of the server (409) */
|
|
124
|
+
CONFLICT: HTTP_CONFLICT,
|
|
125
|
+
/** The resource requested is no longer available and will not be available again (410) */
|
|
126
|
+
GONE: HTTP_GONE,
|
|
127
|
+
/** The request does not meet the preconditions that the server requires (412) */
|
|
128
|
+
PRECONDITION_FAILED: HTTP_PRECONDITION_FAILED,
|
|
129
|
+
/** The client sent a request that is too large for the server to process (413) */
|
|
130
|
+
PAYLOAD_TOO_LARGE: HTTP_PAYLOAD_TOO_LARGE,
|
|
131
|
+
/** The URI requested by the client is too long for the server to process (414) */
|
|
132
|
+
URI_TOO_LONG: HTTP_URI_TOO_LONG,
|
|
133
|
+
/** The media format of the requested data is not supported by the server (415) */
|
|
134
|
+
UNSUPPORTED_MEDIA_TYPE: HTTP_UNSUPPORTED_MEDIA_TYPE,
|
|
135
|
+
/** The range specified by the client cannot be fulfilled (416) */
|
|
136
|
+
RANGE_NOT_SATISFIABLE: HTTP_RANGE_NOT_SATISFIABLE,
|
|
137
|
+
/** The expectation given in the request header could not be met by the server (417) */
|
|
138
|
+
EXPECTATION_FAILED: HTTP_EXPECTATION_FAILED,
|
|
139
|
+
/** The server refuses to brew coffee because it is a teapot (418) - an Easter egg from RFC 2324 */
|
|
140
|
+
IM_A_TEAPOT: HTTP_IM_A_TEAPOT,
|
|
141
|
+
/** The request was well-formed but was unable to be followed due to semantic errors (422) */
|
|
142
|
+
UNPROCESSABLE_ENTITY: HTTP_UNPROCESSABLE_ENTITY,
|
|
143
|
+
/** The resource that is being accessed is locked (423) */
|
|
144
|
+
LOCKED: HTTP_LOCKED,
|
|
145
|
+
/** The resource requested is dependent on another resource that has failed (424) */
|
|
146
|
+
FAILED_DEPENDENCY: HTTP_FAILED_DEPENDENCY,
|
|
147
|
+
/** The server is unwilling to risk processing a request that might be replayed (425) */
|
|
148
|
+
TOO_EARLY: HTTP_TOO_EARLY,
|
|
149
|
+
/** The client needs to upgrade its protocol (426) */
|
|
150
|
+
UPGRADE_REQUIRED: HTTP_UPGRADE_REQUIRED,
|
|
151
|
+
/** The server requires the request to be conditional (428) */
|
|
152
|
+
PRECONDITION_REQUIRED: HTTP_PRECONDITION_REQUIRED,
|
|
153
|
+
/** The client has sent too many requests in a given amount of time (429) */
|
|
154
|
+
TOO_MANY_REQUESTS: HTTP_TOO_MANY_REQUESTS,
|
|
155
|
+
/** The request header fields are too large (431) */
|
|
156
|
+
REQUEST_HEADER_FIELDS_TOO_LARGE: HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
|
|
157
|
+
/** The client closed the connection with the server before the request was completed (444) */
|
|
158
|
+
CONNECTION_CLOSED_WITHOUT_RESPONSE: HTTP_CONNECTION_CLOSED_WITHOUT_RESPONSE,
|
|
159
|
+
/** The client requested an unavailable legal action (451) */
|
|
160
|
+
UNAVAILABLE_FOR_LEGAL_REASONS: HTTP_UNAVAILABLE_FOR_LEGAL_REASONS,
|
|
161
|
+
/** The server encountered an internal error and was unable to complete the request (500) */
|
|
162
|
+
INTERNAL_SERVER_ERROR: HTTP_INTERNAL_SERVER_ERROR,
|
|
163
|
+
/** The request method is not supported by the server and cannot be handled (501) */
|
|
164
|
+
NOT_IMPLEMENTED: HTTP_NOT_IMPLEMENTED,
|
|
165
|
+
/** The server, while acting as a gateway or proxy, received an invalid response from the upstream server (502) */
|
|
166
|
+
BAD_GATEWAY: HTTP_BAD_GATEWAY,
|
|
167
|
+
/** The server is not ready to handle the request, typically due to temporary overload or maintenance (503) */
|
|
168
|
+
SERVICE_UNAVAILABLE: HTTP_SERVICE_UNAVAILABLE,
|
|
169
|
+
/** The server, while acting as a gateway or proxy, did not get a response in time from the upstream server (504) */
|
|
170
|
+
GATEWAY_TIMEOUT: HTTP_GATEWAY_TIMEOUT,
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* Returns the reason phrase corresponding to the given HTTP status code.
|
|
174
|
+
* This is useful for converting status codes into human-readable messages.
|
|
175
|
+
*
|
|
176
|
+
* @param statusCode - The HTTP status code for which to get the reason phrase.
|
|
177
|
+
* @returns The reason phrase associated with the given status code, or "Unknown Status Code" if the status code is not recognized.
|
|
178
|
+
*/
|
|
179
|
+
export const getHttpStatusCodeReasonPhrase = (statusCode) => {
|
|
180
|
+
const phrases = {
|
|
181
|
+
200: 'OK',
|
|
182
|
+
201: 'Created',
|
|
183
|
+
202: 'Accepted',
|
|
184
|
+
204: 'No Content',
|
|
185
|
+
205: 'Reset Content',
|
|
186
|
+
206: 'Partial Content',
|
|
187
|
+
226: 'IM Used',
|
|
188
|
+
301: 'Moved Permanently',
|
|
189
|
+
302: 'Found',
|
|
190
|
+
304: 'Not Modified',
|
|
191
|
+
400: 'Bad Request',
|
|
192
|
+
401: 'Unauthorized',
|
|
193
|
+
403: 'Forbidden',
|
|
194
|
+
404: 'Not Found',
|
|
195
|
+
405: 'Method Not Allowed',
|
|
196
|
+
407: 'Proxy Authentication Required',
|
|
197
|
+
408: 'Request Timeout',
|
|
198
|
+
409: 'Conflict',
|
|
199
|
+
410: 'Gone',
|
|
200
|
+
412: 'Precondition Failed',
|
|
201
|
+
413: 'Payload Too Large',
|
|
202
|
+
414: 'URI Too Long',
|
|
203
|
+
415: 'Unsupported Media Type',
|
|
204
|
+
416: 'Range Not Satisfiable',
|
|
205
|
+
417: 'Expectation Failed',
|
|
206
|
+
418: "I'm a teapot",
|
|
207
|
+
422: 'Unprocessable Entity',
|
|
208
|
+
423: 'Locked',
|
|
209
|
+
424: 'Failed Dependency',
|
|
210
|
+
425: 'Too Early',
|
|
211
|
+
426: 'Upgrade Required',
|
|
212
|
+
428: 'Precondition Required',
|
|
213
|
+
429: 'Too Many Requests',
|
|
214
|
+
431: 'Request Header Fields Too Large',
|
|
215
|
+
444: 'Connection Closed Without Response',
|
|
216
|
+
451: 'Unavailable For Legal Reasons',
|
|
217
|
+
500: 'Internal Server Error',
|
|
218
|
+
501: 'Not Implemented',
|
|
219
|
+
502: 'Bad Gateway',
|
|
220
|
+
503: 'Service Unavailable',
|
|
221
|
+
504: 'Gateway Timeout',
|
|
222
|
+
};
|
|
223
|
+
return phrases[statusCode] || 'Unknown Status Code';
|
|
224
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export * from './api.types';
|
|
2
|
+
export * from './auth/auth-strategy';
|
|
3
|
+
export * from './auth/auth.types';
|
|
4
|
+
export * from './auth/auth.utils';
|
|
5
|
+
export * from './auth/bearer-auth-strategy';
|
|
6
|
+
export * from './config';
|
|
7
|
+
export * from './error-handling';
|
|
8
|
+
export * from './http-status-codes';
|
|
9
|
+
export * from './rate-limit/in-memory-rate-limiter';
|
|
10
|
+
export * from './rate-limit/rate-limit.types';
|
|
11
|
+
export * from './route-table';
|
|
12
|
+
export * from './router';
|
|
13
|
+
export * from './thread-local/thread-local-storage';
|
|
14
|
+
export * from './thread-local/thread-local-storage-middleware';
|
|
15
|
+
export * from './utils/express.utils';
|
package/dist/esm/index.js
CHANGED
|
@@ -5,7 +5,7 @@ export * from './auth/auth.utils';
|
|
|
5
5
|
export * from './auth/bearer-auth-strategy';
|
|
6
6
|
export * from './config';
|
|
7
7
|
export * from './error-handling';
|
|
8
|
-
export * from './http
|
|
8
|
+
export * from './http-status-codes';
|
|
9
9
|
export * from './rate-limit/in-memory-rate-limiter';
|
|
10
10
|
export * from './rate-limit/rate-limit.types';
|
|
11
11
|
export * from './route-table';
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { ExpressFunction } from '../utils/express.utils';
|
|
2
|
+
import { RateLimitConfig, RateLimitResult } from './rate-limit.types';
|
|
3
|
+
/**
|
|
4
|
+
* In-memory rate limiter using sliding window counter.
|
|
5
|
+
* Tracks request counts per key with time-based window expiration.
|
|
6
|
+
*/
|
|
7
|
+
declare class InMemoryRateLimiter {
|
|
8
|
+
private readonly limits;
|
|
9
|
+
private readonly points;
|
|
10
|
+
private readonly durationMs;
|
|
11
|
+
constructor(points: number, durationSeconds: number);
|
|
12
|
+
/**
|
|
13
|
+
* Try to consume points from the rate limit.
|
|
14
|
+
* Returns result if successful, throws if limit exceeded.
|
|
15
|
+
*
|
|
16
|
+
* @param key - Unique identifier for the client (e.g., IP address)
|
|
17
|
+
* @returns Rate limit result with remaining points and ms until reset
|
|
18
|
+
* @throws RateLimitResult if limit exceeded
|
|
19
|
+
*/
|
|
20
|
+
consume(key: string): RateLimitResult;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Creates a rate limiter middleware using in-memory implementation.
|
|
24
|
+
*
|
|
25
|
+
* Separate limiters are used for read (GET) and write (POST/PATCH/PUT/DELETE) requests.
|
|
26
|
+
*
|
|
27
|
+
* @param config - Rate limit configuration
|
|
28
|
+
* @returns Express middleware function
|
|
29
|
+
*/
|
|
30
|
+
export declare function createRateLimiterMiddleware(config: RateLimitConfig): Promise<ExpressFunction>;
|
|
31
|
+
/**
|
|
32
|
+
* Export the in-memory limiter class for advanced use cases where
|
|
33
|
+
* you might want direct control over rate limit management.
|
|
34
|
+
*/
|
|
35
|
+
export { InMemoryRateLimiter };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { ExpressResponse } from '../utils/express.utils';
|
|
2
|
+
import { RateLimitResult } from './rate-limit.types';
|
|
3
|
+
/**
|
|
4
|
+
* Adds rate limit state headers to the response.
|
|
5
|
+
* See https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/
|
|
6
|
+
*
|
|
7
|
+
* Headers added:
|
|
8
|
+
* - X-RateLimit-Limit: Server's quota for requests in the time window
|
|
9
|
+
* - X-RateLimit-Remaining: Remaining quota in the current window
|
|
10
|
+
* - X-RateLimit-Reset: Time remaining in the current window (in seconds)
|
|
11
|
+
* - X-RateLimit-Policy: Quota policies associated with the client
|
|
12
|
+
* @Internal
|
|
13
|
+
*/
|
|
14
|
+
export declare function addRateLimitHeaders(res: ExpressResponse, result: RateLimitResult, limitPoints: number, duration: number): ExpressResponse;
|
|
15
|
+
/**
|
|
16
|
+
* Converts milliseconds to seconds, rounding up.
|
|
17
|
+
* @Internal
|
|
18
|
+
*/
|
|
19
|
+
export declare function msToSeconds(ms: number): number;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration for rate limiting.
|
|
3
|
+
*/
|
|
4
|
+
export interface RateLimitConfig {
|
|
5
|
+
/** Rate limit points per time window */
|
|
6
|
+
points: {
|
|
7
|
+
read: number;
|
|
8
|
+
write: number;
|
|
9
|
+
};
|
|
10
|
+
/** Duration of the rate limit window in seconds */
|
|
11
|
+
duration: number;
|
|
12
|
+
/** Key prefix for rate limit data (optional, defaults to 'rate_limit') */
|
|
13
|
+
keyPrefix?: string;
|
|
14
|
+
/** Paths that should bypass rate limiting (default: ['/v1', '/health']) */
|
|
15
|
+
rateLimitWhitelist?: string[];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Simple in-memory rate limiter result.
|
|
19
|
+
*/
|
|
20
|
+
export interface RateLimitResult {
|
|
21
|
+
remainingPoints: number;
|
|
22
|
+
msBeforeNext: number;
|
|
23
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ExpressApplication } from './utils/express.utils';
|
|
2
|
+
import { DeleteEndpoint, GetEndpoint, PatchEndpoint, PostEndpoint, PutEndpoint, RequestContext, ResponseOrValue } from './router';
|
|
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: ExpressApplication);
|
|
10
|
+
get<T>(path: string, endpoint: GetEndpoint<T> | GetEndpoint<T[]>): this;
|
|
11
|
+
get<T>(path: string, run: (ctx: RequestContext) => Promise<ResponseOrValue<T>>): this;
|
|
12
|
+
post<Body, Result>(path: string, endpoint: PostEndpoint<Body, Result>): this;
|
|
13
|
+
patch<Body, Result>(path: string, endpoint: PatchEndpoint<Body, Result>): this;
|
|
14
|
+
put<Body, Result>(path: string, endpoint: PutEndpoint<Body, Result>): this;
|
|
15
|
+
delete(path: string, endpoint: DeleteEndpoint): this;
|
|
16
|
+
delete(path: string, run: (ctx: RequestContext) => Promise<void>): this;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Factory function to create a new route table.
|
|
20
|
+
* @param app Express application instance
|
|
21
|
+
* @returns RouteTable instance with fluent API
|
|
22
|
+
*/
|
|
23
|
+
export declare function createRouteTable(app: ExpressApplication): RouteTable;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { Assertion, ObjectAssertion } from '@fishka/assertions';
|
|
2
|
+
import { ApiResponse, UrlTokensValidator } from './api.types';
|
|
3
|
+
import { AuthUser } from './auth/auth.types';
|
|
4
|
+
import { ExpressApplication, ExpressRequest, ExpressResponse } from './utils/express.utils';
|
|
5
|
+
/** Express API allows handlers to return response in the raw form. */
|
|
6
|
+
export type ResponseOrValue<ResponseEntity> = ApiResponse<ResponseEntity> | ResponseEntity;
|
|
7
|
+
/**
|
|
8
|
+
* Generic middleware hook for endpoint execution.
|
|
9
|
+
* Allows custom logic like transaction management, authorization checks, etc.
|
|
10
|
+
*/
|
|
11
|
+
export type EndpointMiddleware<Context = RequestContext> = (run: () => Promise<unknown>, context: Context) => Promise<unknown>;
|
|
12
|
+
/** Generic request context passed to all handlers. Database-agnostic and extensible. */
|
|
13
|
+
export interface RequestContext<Body = void> {
|
|
14
|
+
/** Parsed and validated request body (for POST/PATCH/PUT handlers). */
|
|
15
|
+
body: Body;
|
|
16
|
+
/** Express Request object. */
|
|
17
|
+
req: ExpressRequest;
|
|
18
|
+
/** Express Response object. */
|
|
19
|
+
res: ExpressResponse;
|
|
20
|
+
/** Authenticated user (if any). Populated by auth middleware. */
|
|
21
|
+
authUser?: AuthUser;
|
|
22
|
+
/**
|
|
23
|
+
* Generic parameter access with lazy validation.
|
|
24
|
+
* Provides type-safe access to URL path and query parameters.
|
|
25
|
+
*/
|
|
26
|
+
params: {
|
|
27
|
+
get(key: string): string;
|
|
28
|
+
tryGet(key: string): string | undefined;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Query parameter access.
|
|
32
|
+
*/
|
|
33
|
+
query: {
|
|
34
|
+
get(key: string): string | undefined;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Generic state storage for middleware to attach data.
|
|
38
|
+
* Allows middleware to pass information to handlers and other middleware.
|
|
39
|
+
*/
|
|
40
|
+
state: Map<string, unknown>;
|
|
41
|
+
}
|
|
42
|
+
/** Base interface with common endpoint properties. */
|
|
43
|
+
export interface EndpointBase<Context = RequestContext, Result = unknown> {
|
|
44
|
+
/** Path parameter validator. */
|
|
45
|
+
$path?: UrlTokensValidator;
|
|
46
|
+
/** Query parameter validator. */
|
|
47
|
+
$query?: UrlTokensValidator;
|
|
48
|
+
/** Optional middleware to execute before the handler. */
|
|
49
|
+
middlewares?: Array<EndpointMiddleware>;
|
|
50
|
+
/** Handler function. */
|
|
51
|
+
run: (ctx: Context) => Promise<ResponseOrValue<Result>>;
|
|
52
|
+
}
|
|
53
|
+
/** Descriptor for GET list routes. */
|
|
54
|
+
export type GetListEndpoint<ResultElementType = unknown> = EndpointBase<RequestContext, Array<ResultElementType>>;
|
|
55
|
+
/** Descriptor for GET routes. */
|
|
56
|
+
export type GetEndpoint<Result = unknown> = EndpointBase<RequestContext, Result>;
|
|
57
|
+
/** Descriptor for POST routes. */
|
|
58
|
+
export interface PostEndpoint<Body = unknown, Result = unknown> extends EndpointBase<RequestContext<Body>, Result> {
|
|
59
|
+
/** Request body validator. */
|
|
60
|
+
$body: Body extends object ? ObjectAssertion<Body> : Assertion<Body>;
|
|
61
|
+
}
|
|
62
|
+
/** Same as POST. Used for full object updates. */
|
|
63
|
+
export type PutEndpoint<Body = unknown, Result = unknown> = PostEndpoint<Body, Result>;
|
|
64
|
+
/** Same as PUT. While PUT is used for the whole object update, PATCH is used for a partial update. */
|
|
65
|
+
export type PatchEndpoint<Body = unknown, Result = unknown> = PutEndpoint<Body, Result>;
|
|
66
|
+
/** Descriptor for DELETE routes. */
|
|
67
|
+
export type DeleteEndpoint = EndpointBase<RequestContext, void>;
|
|
68
|
+
/** Union type for all route registration info objects. */
|
|
69
|
+
export type RouteRegistrationInfo = ({
|
|
70
|
+
method: 'get';
|
|
71
|
+
route: GetEndpoint | GetListEndpoint;
|
|
72
|
+
} | {
|
|
73
|
+
method: 'post';
|
|
74
|
+
route: PostEndpoint;
|
|
75
|
+
} | {
|
|
76
|
+
method: 'patch';
|
|
77
|
+
route: PatchEndpoint;
|
|
78
|
+
} | {
|
|
79
|
+
method: 'put';
|
|
80
|
+
route: PutEndpoint;
|
|
81
|
+
} | {
|
|
82
|
+
method: 'delete';
|
|
83
|
+
route: DeleteEndpoint;
|
|
84
|
+
}) & {
|
|
85
|
+
path: string;
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* Registers a GET route.
|
|
89
|
+
*/
|
|
90
|
+
export declare const mountGet: (app: ExpressApplication, path: string, endpoint: GetEndpoint | GetListEndpoint) => void;
|
|
91
|
+
/**
|
|
92
|
+
* Registers a POST route.
|
|
93
|
+
*/
|
|
94
|
+
export declare const mountPost: <Body, Result>(app: ExpressApplication, path: string, endpoint: PostEndpoint<Body, Result>) => void;
|
|
95
|
+
/**
|
|
96
|
+
* Registers a PATCH route.
|
|
97
|
+
*/
|
|
98
|
+
export declare const mountPatch: <Body, Result>(app: ExpressApplication, path: string, endpoint: PatchEndpoint<Body, Result>) => void;
|
|
99
|
+
/**
|
|
100
|
+
* Registers a PUT route.
|
|
101
|
+
*/
|
|
102
|
+
export declare const mountPut: <Body, Result>(app: ExpressApplication, path: string, endpoint: PutEndpoint<Body, Result>) => void;
|
|
103
|
+
/**
|
|
104
|
+
* Registers a DELETE route.
|
|
105
|
+
*/
|
|
106
|
+
export declare const mountDelete: (app: ExpressApplication, path: string, endpoint: DeleteEndpoint) => void;
|
|
107
|
+
/**
|
|
108
|
+
* Mounts a route with the given method, endpoint, and path.
|
|
109
|
+
*/
|
|
110
|
+
export declare function mount(app: ExpressApplication, { method, route, path }: RouteRegistrationInfo): void;
|
package/dist/esm/router.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { assertTruthy, callValueAssertion, getMessageFromError, validateObject, } from '@fishka/assertions';
|
|
2
2
|
import * as url from 'url';
|
|
3
|
-
import { HttpError, URL_PARAMETER_INFO } from './api.types';
|
|
4
|
-
import {
|
|
3
|
+
import { HttpError, URL_PARAMETER_INFO, assertHttp } from './api.types';
|
|
4
|
+
import { HTTP_BAD_REQUEST, HTTP_OK } from './http-status-codes';
|
|
5
5
|
import { catchRouteErrors } from './error-handling';
|
|
6
6
|
import { getRequestLocalStorage } from './thread-local/thread-local-storage';
|
|
7
7
|
import { wrapAsApiResponse } from './utils/conversion.utils';
|
|
@@ -61,7 +61,7 @@ function createRouteHandler(method, endpoint) {
|
|
|
61
61
|
if (tls?.requestId) {
|
|
62
62
|
response.requestId = tls.requestId;
|
|
63
63
|
}
|
|
64
|
-
response.status = response.status ||
|
|
64
|
+
response.status = response.status || HTTP_OK;
|
|
65
65
|
res.status(response.status);
|
|
66
66
|
res.send(response);
|
|
67
67
|
};
|
|
@@ -77,12 +77,12 @@ function validateUrlParameters(req, { $path, $query, }) {
|
|
|
77
77
|
// Run Global Validation if registered.
|
|
78
78
|
const globalValidator = URL_PARAMETER_INFO[key]?.validator;
|
|
79
79
|
if (globalValidator) {
|
|
80
|
-
callValueAssertion(value, globalValidator, `${
|
|
80
|
+
callValueAssertion(value, globalValidator, `${HTTP_BAD_REQUEST}`);
|
|
81
81
|
}
|
|
82
82
|
// Run Local Validation.
|
|
83
83
|
const validator = $path?.[key];
|
|
84
84
|
if (validator) {
|
|
85
|
-
callValueAssertion(value, validator, `${
|
|
85
|
+
callValueAssertion(value, validator, `${HTTP_BAD_REQUEST}`);
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
const parsedUrl = url.parse(req.url, true);
|
|
@@ -94,16 +94,16 @@ function validateUrlParameters(req, { $path, $query, }) {
|
|
|
94
94
|
// Query params can be string | string[] | undefined. Global validators usually expect string.
|
|
95
95
|
// We only validate if it's a single value or handle array in validator.
|
|
96
96
|
// For simplicity, we pass value as is (unknown) to assertion.
|
|
97
|
-
callValueAssertion(value, globalValidator, `${
|
|
97
|
+
callValueAssertion(value, globalValidator, `${HTTP_BAD_REQUEST}`);
|
|
98
98
|
}
|
|
99
99
|
const validator = $query?.[key];
|
|
100
100
|
if (validator) {
|
|
101
|
-
callValueAssertion(value, validator, `${
|
|
101
|
+
callValueAssertion(value, validator, `${HTTP_BAD_REQUEST}`);
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
104
|
}
|
|
105
105
|
catch (error) {
|
|
106
|
-
throw new HttpError(
|
|
106
|
+
throw new HttpError(HTTP_BAD_REQUEST, getMessageFromError(error));
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
109
|
/**
|
|
@@ -136,23 +136,23 @@ async function executeBodyEndpoint(route, req, res) {
|
|
|
136
136
|
// Handle validation based on whether validator is an object or function
|
|
137
137
|
if (typeof validator === 'function') {
|
|
138
138
|
// It's a ValueAssertion (function)
|
|
139
|
-
callValueAssertion(apiRequest, validator, `${
|
|
139
|
+
callValueAssertion(apiRequest, validator, `${HTTP_BAD_REQUEST}: request body`);
|
|
140
140
|
}
|
|
141
141
|
else {
|
|
142
142
|
// It's an ObjectAssertion - use validateObject
|
|
143
143
|
// We strictly assume it is an object because of the type definition (function | object)
|
|
144
144
|
const objectValidator = validator;
|
|
145
145
|
const isEmptyValidator = Object.keys(objectValidator).length === 0;
|
|
146
|
-
const
|
|
146
|
+
const errorMessage = validateObject(apiRequest, objectValidator, `${HTTP_BAD_REQUEST}: request body`, {
|
|
147
147
|
failOnUnknownFields: !isEmptyValidator,
|
|
148
148
|
});
|
|
149
|
-
|
|
149
|
+
assertHttp(!errorMessage, HTTP_BAD_REQUEST, errorMessage || 'Request body validation failed');
|
|
150
150
|
}
|
|
151
151
|
}
|
|
152
152
|
catch (error) {
|
|
153
153
|
if (error instanceof HttpError)
|
|
154
154
|
throw error;
|
|
155
|
-
throw new HttpError(
|
|
155
|
+
throw new HttpError(HTTP_BAD_REQUEST, getMessageFromError(error));
|
|
156
156
|
}
|
|
157
157
|
const requestContext = newRequestContext(apiRequest, req, res);
|
|
158
158
|
validateUrlParameters(req, { $path: route.$path, $query: route.$query });
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ExpressFunction } from '../utils/express.utils';
|
|
2
|
+
/**
|
|
3
|
+
* Creates middleware that initializes thread-local storage for each request.
|
|
4
|
+
* Automatically generates a unique request ID and makes it available throughout
|
|
5
|
+
* the request lifecycle.
|
|
6
|
+
*
|
|
7
|
+
* @returns Express middleware function
|
|
8
|
+
*/
|
|
9
|
+
export declare function createTlsMiddleware(): ExpressFunction;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thread-local storage data for per-request context.
|
|
3
|
+
* Stores information that should be available throughout the request lifecycle.
|
|
4
|
+
*/
|
|
5
|
+
export interface ThreadLocalData {
|
|
6
|
+
/** Unique request identifier */
|
|
7
|
+
requestId: string;
|
|
8
|
+
/** Additional custom fields can be stored */
|
|
9
|
+
[key: string]: unknown;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Gets all thread-local data for the current request context.
|
|
13
|
+
* Returns undefined if called outside an async context managed by API.
|
|
14
|
+
* @Internal
|
|
15
|
+
*/
|
|
16
|
+
export declare function getRequestLocalStorage(): ThreadLocalData | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* Executes a callback within a request context with the given thread-local data.
|
|
19
|
+
* Used by middleware to set up the context for handlers.
|
|
20
|
+
* @Internal
|
|
21
|
+
* @param data - Thread-local data to establish
|
|
22
|
+
* @param callback - Function to execute within the context
|
|
23
|
+
* @returns Result of the callback
|
|
24
|
+
*/
|
|
25
|
+
export declare function runWithRequestTlsData<T>(data: ThreadLocalData, callback: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ApiResponse } from '../api.types';
|
|
2
|
+
/**
|
|
3
|
+
* Converts JS timestamp or date to ISO 8601 format (without milliseconds).
|
|
4
|
+
* Example: "2012-07-20T01:19:13Z".
|
|
5
|
+
* @Internal
|
|
6
|
+
*/
|
|
7
|
+
export declare function toApiDateString(value: number | Date): string;
|
|
8
|
+
/**
|
|
9
|
+
* Wraps the response into the correct API form.
|
|
10
|
+
* Add necessary fields, like 'requestId'.
|
|
11
|
+
* If the response is already in the correct form, returns it as-is.
|
|
12
|
+
* @Internal
|
|
13
|
+
*/
|
|
14
|
+
export declare function wrapAsApiResponse<T = unknown>(apiResponseOrResultValue: T | ApiResponse<T>): ApiResponse<T>;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
/** Shortcut for express.* types with no namespace: so the type can be found/imported by IDE. */
|
|
3
|
+
export type ExpressRequest = express.Request;
|
|
4
|
+
export type ExpressResponse = express.Response;
|
|
5
|
+
export type ExpressNextFunction = express.NextFunction;
|
|
6
|
+
export type ExpressApplication = express.Application;
|
|
7
|
+
export type ExpressFunction = (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => Promise<void>;
|
package/package.json
CHANGED
package/dist/cjs/http.types.js
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.TOO_MANY_REQUESTS_STATUS = exports.OK_STATUS = exports.NOT_FOUND_STATUS = exports.FORBIDDEN_STATUS = exports.UNAUTHORIZED_STATUS = exports.BAD_REQUEST_STATUS = exports.INTERNAL_ERROR_STATUS = void 0;
|
|
4
|
-
/**
|
|
5
|
-
* Common HTTP status codes as numbers.
|
|
6
|
-
* @Internal
|
|
7
|
-
*/
|
|
8
|
-
exports.INTERNAL_ERROR_STATUS = 500;
|
|
9
|
-
/**
|
|
10
|
-
* Common HTTP status codes as numbers.
|
|
11
|
-
* @Internal
|
|
12
|
-
*/
|
|
13
|
-
exports.BAD_REQUEST_STATUS = 400;
|
|
14
|
-
/**
|
|
15
|
-
* Common HTTP status codes as numbers.
|
|
16
|
-
* @Internal
|
|
17
|
-
*/
|
|
18
|
-
exports.UNAUTHORIZED_STATUS = 401;
|
|
19
|
-
/**
|
|
20
|
-
* Common HTTP status codes as numbers.
|
|
21
|
-
* @Internal
|
|
22
|
-
*/
|
|
23
|
-
exports.FORBIDDEN_STATUS = 403;
|
|
24
|
-
/**
|
|
25
|
-
* Common HTTP status codes as numbers.
|
|
26
|
-
* @Internal
|
|
27
|
-
*/
|
|
28
|
-
exports.NOT_FOUND_STATUS = 404;
|
|
29
|
-
/**
|
|
30
|
-
* Common HTTP status codes as numbers.
|
|
31
|
-
* @Internal
|
|
32
|
-
*/
|
|
33
|
-
exports.OK_STATUS = 200;
|
|
34
|
-
/**
|
|
35
|
-
* Common HTTP status codes as numbers.
|
|
36
|
-
* @Internal
|
|
37
|
-
*/
|
|
38
|
-
exports.TOO_MANY_REQUESTS_STATUS = 429;
|