@web-ts-toolkit/express-json-router 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright © 2017, Province of British Columbia, Canada.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # @web-ts-toolkit/express-json-router
2
+
3
+ Express router wrapper that wires route handlers through `@web-ts-toolkit/express-response-handler` and keeps track of registered endpoints.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ pnpm add @web-ts-toolkit/express-json-router express
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import express from 'express';
15
+ import JsonRouter from '@web-ts-toolkit/express-json-router';
16
+
17
+ const app = express();
18
+ const router = new JsonRouter('/api');
19
+
20
+ router.get('/health', () => ({ ok: true }));
21
+
22
+ router.get('/users/:id', () => {
23
+ throw new JsonRouter.clientErrors.NotFoundError('User not found');
24
+ });
25
+
26
+ JsonRouter.errorMessageProvider = (error) => {
27
+ if (error instanceof Error) {
28
+ return { message: error.message };
29
+ }
30
+
31
+ return { message: String(error) };
32
+ };
33
+
34
+ app.use(router.original);
35
+ ```
36
+
37
+ ## Behavior
38
+
39
+ - Route handlers can return plain values, promises, `JsonRouter.HttpResponse.*` helpers, or throw `JsonRouter.clientErrors.*` errors.
40
+ - Router-level middleware can be passed as a single function or an array in the constructor.
41
+ - `router.route(path)` supports the same JSON-aware handler behavior as `router.get(path, ...)`, `router.post(path, ...)`, and the other Express router methods exposed by the instance.
42
+ - `router.getEndpoints()` returns a snapshot of the registered endpoints in registration order.
43
+
44
+ ## Hooks
45
+
46
+ The package forwards the shared hooks from `@web-ts-toolkit/express-response-handler` through static properties on `JsonRouter`.
47
+
48
+ ```ts
49
+ JsonRouter.preJson = (value) => {
50
+ console.log('about to serialize', value);
51
+ };
52
+
53
+ JsonRouter.postJson = (value) => {
54
+ console.log('serialized', value);
55
+ };
56
+
57
+ JsonRouter.preError = (error) => {
58
+ console.error('request failed', error);
59
+ };
60
+ ```
61
+
62
+ These hooks are shared process-wide because they proxy the default response-handler instance.
63
+
64
+ ## API
65
+
66
+ `new JsonRouter(basePath?, middlewares?)`
67
+
68
+ Creates a JSON-aware Express router. `basePath` accepts values like `'/api'`, `'api'`, or `'api/'` and is normalized for route registration.
69
+
70
+ `router.original`
71
+
72
+ Returns the underlying Express router so it can be mounted with `app.use(...)`.
73
+
74
+ `router.route(path)`
75
+
76
+ Builds chained route registrations such as `router.route('/users').get(...).post(...)`.
77
+
78
+ `router.getEndpoints()`
79
+
80
+ Returns `{ method, path }[]` for the routes registered through `JsonRouter`.
81
+
82
+ `JsonRouter.clientErrors`
83
+
84
+ Re-exports the HTTP error classes from `@web-ts-toolkit/http-errors`.
85
+
86
+ `JsonRouter.success`
87
+
88
+ Re-exports success response classes such as `JsonRouter.success.Created`.
89
+
90
+ `JsonRouter.HttpResponse`
91
+
92
+ Exposes helper constructors such as `JsonRouter.HttpResponse.ok(...)` and `JsonRouter.HttpResponse.created(...)`.
93
+
94
+ `JsonRouter.errorMessageProvider`
95
+
96
+ Overrides the error-to-payload mapping used for non-HTTP errors.
97
+
98
+ `JsonRouter.preJson`, `JsonRouter.postJson`, `JsonRouter.preError`, `JsonRouter.postError`
99
+
100
+ Expose the shared serialization and error hooks from `@web-ts-toolkit/express-response-handler`.
package/index.d.mts ADDED
@@ -0,0 +1,127 @@
1
+ import * as _web_ts_toolkit_express_response_handler_responses_csv from '@web-ts-toolkit/express-response-handler/responses/csv';
2
+ import apiHandler from '@web-ts-toolkit/express-response-handler';
3
+ import { OK, Created, Accepted, NonAuthoritativeInfo, NoContent, ResetContent, PartialContent, MultiStatus, AlreadyReported, IMUsed } from '@web-ts-toolkit/express-response-handler/responses/success';
4
+ import * as clientErrors from '@web-ts-toolkit/http-errors';
5
+ import express, { Request, Response, NextFunction } from 'express';
6
+
7
+ declare const METHODS: readonly ["all", "checkout", "copy", "delete", "get", "head", "lock", "merge", "mkactivity", "mkcol", "move", "m-search", "notify", "options", "patch", "post", "purge", "put", "report", "search", "subscribe", "trace", "unlock", "unsubscribe"];
8
+ type RouteMethod = (typeof METHODS)[number];
9
+ type JsonRouterCallback = (req: Request, res: Response, next: NextFunction) => unknown | Promise<unknown>;
10
+ type RouteRegistrar = (path: string, ...callbacks: JsonRouterCallback[]) => JsonRouter;
11
+ type JsonRouteBuilder = {
12
+ [Method in RouteMethod]: (...callbacks: JsonRouterCallback[]) => JsonRouteBuilder;
13
+ };
14
+ type Endpoint = {
15
+ method: Uppercase<RouteMethod>;
16
+ path: string;
17
+ };
18
+ type ExpressRouter = ReturnType<typeof express.Router>;
19
+ declare class JsonRouter {
20
+ readonly methods: RouteMethod[];
21
+ readonly endpoints: Endpoint[];
22
+ readonly middlewares: JsonRouterCallback[];
23
+ readonly basePath: string;
24
+ all: RouteRegistrar;
25
+ checkout: RouteRegistrar;
26
+ copy: RouteRegistrar;
27
+ delete: RouteRegistrar;
28
+ get: RouteRegistrar;
29
+ head: RouteRegistrar;
30
+ lock: RouteRegistrar;
31
+ merge: RouteRegistrar;
32
+ mkactivity: RouteRegistrar;
33
+ mkcol: RouteRegistrar;
34
+ move: RouteRegistrar;
35
+ ['m-search']: RouteRegistrar;
36
+ notify: RouteRegistrar;
37
+ options: RouteRegistrar;
38
+ patch: RouteRegistrar;
39
+ post: RouteRegistrar;
40
+ purge: RouteRegistrar;
41
+ put: RouteRegistrar;
42
+ report: RouteRegistrar;
43
+ search: RouteRegistrar;
44
+ subscribe: RouteRegistrar;
45
+ trace: RouteRegistrar;
46
+ unlock: RouteRegistrar;
47
+ unsubscribe: RouteRegistrar;
48
+ private readonly _router;
49
+ static readonly clientErrors: typeof clientErrors;
50
+ static readonly success: {
51
+ OK: typeof OK;
52
+ Created: typeof Created;
53
+ Accepted: typeof Accepted;
54
+ NonAuthoritativeInfo: typeof NonAuthoritativeInfo;
55
+ NoContent: typeof NoContent;
56
+ ResetContent: typeof ResetContent;
57
+ PartialContent: typeof PartialContent;
58
+ MultiStatus: typeof MultiStatus;
59
+ AlreadyReported: typeof AlreadyReported;
60
+ IMUsed: typeof IMUsed;
61
+ };
62
+ static readonly HttpResponse: {
63
+ ok: (data: unknown) => OK<unknown>;
64
+ created: (data: unknown) => Created<unknown>;
65
+ accepted: (data: unknown) => Accepted<unknown>;
66
+ nonAuthoritativeInfo: (data: unknown) => NonAuthoritativeInfo<unknown>;
67
+ noContent: (data: unknown) => NoContent<unknown>;
68
+ resetContent: (data: unknown) => ResetContent<unknown>;
69
+ partialContent: (data: unknown) => PartialContent<unknown>;
70
+ multiStatus: (data: unknown) => MultiStatus<unknown>;
71
+ alreadyReported: (data: unknown) => AlreadyReported<unknown>;
72
+ imUsed: (data: unknown) => IMUsed<unknown>;
73
+ badRequest: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.BadRequestError;
74
+ unauthorized: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UnauthorizedError;
75
+ forbidden: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.ForbiddenError;
76
+ notFound: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.NotFoundError;
77
+ methodNotAllowed: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.MethodNotAllowedError;
78
+ notAcceptable: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.NotAcceptableError;
79
+ proxyAuthRequired: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.ProxyAuthRequiredError;
80
+ requestTimeout: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.RequestTimeoutError;
81
+ conflict: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.ConflictError;
82
+ gone: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.GoneError;
83
+ lengthRequired: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.LengthRequiredError;
84
+ preconditionFailed: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.PreconditionFailedError;
85
+ payloadTooLarge: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.PayloadTooLargeError;
86
+ uriTooLong: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UriTooLongError;
87
+ unsupportedMediaType: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UnsupportedMediaTypeError;
88
+ requestedRangeNotSatisfiable: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.RequestedRangeNotSatisfiableError;
89
+ expectationFailed: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.ExpectationFailedError;
90
+ teapot: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.TeapotError;
91
+ misdirectedRequest: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.MisdirectedRequestError;
92
+ unprocessableEntity: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UnprocessableEntityError;
93
+ locked: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.LockedError;
94
+ failedDependency: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.FailedDependencyError;
95
+ upgradeRequired: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UpgradeRequiredError;
96
+ preconditionRequired: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.PreconditionRequiredError;
97
+ tooManyRequests: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.TooManyRequestsError;
98
+ requestHeaderFieldsTooLarge: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.RequestHeaderFieldsTooLargeError;
99
+ unavailableForLegalReasons: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UnavailableForLegalReasonsError;
100
+ json: (data: unknown) => OK<unknown>;
101
+ csv: (dataset?: unknown, options?: {
102
+ filename?: string;
103
+ headers?: boolean;
104
+ processor?: (value: unknown) => unknown;
105
+ } | undefined) => _web_ts_toolkit_express_response_handler_responses_csv.CSVResponse;
106
+ };
107
+ static get errorMessageProvider(): typeof apiHandler.errorMessageProvider;
108
+ static set errorMessageProvider(customErrorMessageProvider: typeof apiHandler.errorMessageProvider);
109
+ static get preJson(): typeof apiHandler.preJson;
110
+ static set preJson(preJsonHookFn: typeof apiHandler.preJson);
111
+ static get postJson(): typeof apiHandler.postJson;
112
+ static set postJson(postJsonHookFn: typeof apiHandler.postJson);
113
+ static get preError(): typeof apiHandler.preError;
114
+ static set preError(preErrorHookFn: typeof apiHandler.preError);
115
+ static get postError(): typeof apiHandler.postError;
116
+ static set postError(postErrorHookFn: typeof apiHandler.postError);
117
+ constructor(basePath?: string, middlewares?: JsonRouterCallback | JsonRouterCallback[]);
118
+ get original(): ExpressRouter;
119
+ param(...args: Parameters<ExpressRouter['param']>): ReturnType<ExpressRouter['param']>;
120
+ use(...args: Parameters<ExpressRouter['use']>): ReturnType<ExpressRouter['use']>;
121
+ route(path: string): JsonRouteBuilder;
122
+ addEndpoint(method: RouteMethod, path: string): void;
123
+ getEndpoints(): Endpoint[];
124
+ normalizePath(path: string): string;
125
+ }
126
+
127
+ export { JsonRouter as default };
package/index.d.ts ADDED
@@ -0,0 +1,127 @@
1
+ import * as _web_ts_toolkit_express_response_handler_responses_csv from '@web-ts-toolkit/express-response-handler/responses/csv';
2
+ import apiHandler from '@web-ts-toolkit/express-response-handler';
3
+ import { OK, Created, Accepted, NonAuthoritativeInfo, NoContent, ResetContent, PartialContent, MultiStatus, AlreadyReported, IMUsed } from '@web-ts-toolkit/express-response-handler/responses/success';
4
+ import * as clientErrors from '@web-ts-toolkit/http-errors';
5
+ import express, { Request, Response, NextFunction } from 'express';
6
+
7
+ declare const METHODS: readonly ["all", "checkout", "copy", "delete", "get", "head", "lock", "merge", "mkactivity", "mkcol", "move", "m-search", "notify", "options", "patch", "post", "purge", "put", "report", "search", "subscribe", "trace", "unlock", "unsubscribe"];
8
+ type RouteMethod = (typeof METHODS)[number];
9
+ type JsonRouterCallback = (req: Request, res: Response, next: NextFunction) => unknown | Promise<unknown>;
10
+ type RouteRegistrar = (path: string, ...callbacks: JsonRouterCallback[]) => JsonRouter;
11
+ type JsonRouteBuilder = {
12
+ [Method in RouteMethod]: (...callbacks: JsonRouterCallback[]) => JsonRouteBuilder;
13
+ };
14
+ type Endpoint = {
15
+ method: Uppercase<RouteMethod>;
16
+ path: string;
17
+ };
18
+ type ExpressRouter = ReturnType<typeof express.Router>;
19
+ declare class JsonRouter {
20
+ readonly methods: RouteMethod[];
21
+ readonly endpoints: Endpoint[];
22
+ readonly middlewares: JsonRouterCallback[];
23
+ readonly basePath: string;
24
+ all: RouteRegistrar;
25
+ checkout: RouteRegistrar;
26
+ copy: RouteRegistrar;
27
+ delete: RouteRegistrar;
28
+ get: RouteRegistrar;
29
+ head: RouteRegistrar;
30
+ lock: RouteRegistrar;
31
+ merge: RouteRegistrar;
32
+ mkactivity: RouteRegistrar;
33
+ mkcol: RouteRegistrar;
34
+ move: RouteRegistrar;
35
+ ['m-search']: RouteRegistrar;
36
+ notify: RouteRegistrar;
37
+ options: RouteRegistrar;
38
+ patch: RouteRegistrar;
39
+ post: RouteRegistrar;
40
+ purge: RouteRegistrar;
41
+ put: RouteRegistrar;
42
+ report: RouteRegistrar;
43
+ search: RouteRegistrar;
44
+ subscribe: RouteRegistrar;
45
+ trace: RouteRegistrar;
46
+ unlock: RouteRegistrar;
47
+ unsubscribe: RouteRegistrar;
48
+ private readonly _router;
49
+ static readonly clientErrors: typeof clientErrors;
50
+ static readonly success: {
51
+ OK: typeof OK;
52
+ Created: typeof Created;
53
+ Accepted: typeof Accepted;
54
+ NonAuthoritativeInfo: typeof NonAuthoritativeInfo;
55
+ NoContent: typeof NoContent;
56
+ ResetContent: typeof ResetContent;
57
+ PartialContent: typeof PartialContent;
58
+ MultiStatus: typeof MultiStatus;
59
+ AlreadyReported: typeof AlreadyReported;
60
+ IMUsed: typeof IMUsed;
61
+ };
62
+ static readonly HttpResponse: {
63
+ ok: (data: unknown) => OK<unknown>;
64
+ created: (data: unknown) => Created<unknown>;
65
+ accepted: (data: unknown) => Accepted<unknown>;
66
+ nonAuthoritativeInfo: (data: unknown) => NonAuthoritativeInfo<unknown>;
67
+ noContent: (data: unknown) => NoContent<unknown>;
68
+ resetContent: (data: unknown) => ResetContent<unknown>;
69
+ partialContent: (data: unknown) => PartialContent<unknown>;
70
+ multiStatus: (data: unknown) => MultiStatus<unknown>;
71
+ alreadyReported: (data: unknown) => AlreadyReported<unknown>;
72
+ imUsed: (data: unknown) => IMUsed<unknown>;
73
+ badRequest: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.BadRequestError;
74
+ unauthorized: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UnauthorizedError;
75
+ forbidden: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.ForbiddenError;
76
+ notFound: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.NotFoundError;
77
+ methodNotAllowed: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.MethodNotAllowedError;
78
+ notAcceptable: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.NotAcceptableError;
79
+ proxyAuthRequired: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.ProxyAuthRequiredError;
80
+ requestTimeout: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.RequestTimeoutError;
81
+ conflict: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.ConflictError;
82
+ gone: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.GoneError;
83
+ lengthRequired: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.LengthRequiredError;
84
+ preconditionFailed: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.PreconditionFailedError;
85
+ payloadTooLarge: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.PayloadTooLargeError;
86
+ uriTooLong: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UriTooLongError;
87
+ unsupportedMediaType: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UnsupportedMediaTypeError;
88
+ requestedRangeNotSatisfiable: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.RequestedRangeNotSatisfiableError;
89
+ expectationFailed: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.ExpectationFailedError;
90
+ teapot: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.TeapotError;
91
+ misdirectedRequest: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.MisdirectedRequestError;
92
+ unprocessableEntity: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UnprocessableEntityError;
93
+ locked: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.LockedError;
94
+ failedDependency: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.FailedDependencyError;
95
+ upgradeRequired: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UpgradeRequiredError;
96
+ preconditionRequired: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.PreconditionRequiredError;
97
+ tooManyRequests: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.TooManyRequestsError;
98
+ requestHeaderFieldsTooLarge: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.RequestHeaderFieldsTooLargeError;
99
+ unavailableForLegalReasons: (message?: string | undefined, options?: clientErrors.HttpErrorOptions | undefined) => clientErrors.UnavailableForLegalReasonsError;
100
+ json: (data: unknown) => OK<unknown>;
101
+ csv: (dataset?: unknown, options?: {
102
+ filename?: string;
103
+ headers?: boolean;
104
+ processor?: (value: unknown) => unknown;
105
+ } | undefined) => _web_ts_toolkit_express_response_handler_responses_csv.CSVResponse;
106
+ };
107
+ static get errorMessageProvider(): typeof apiHandler.errorMessageProvider;
108
+ static set errorMessageProvider(customErrorMessageProvider: typeof apiHandler.errorMessageProvider);
109
+ static get preJson(): typeof apiHandler.preJson;
110
+ static set preJson(preJsonHookFn: typeof apiHandler.preJson);
111
+ static get postJson(): typeof apiHandler.postJson;
112
+ static set postJson(postJsonHookFn: typeof apiHandler.postJson);
113
+ static get preError(): typeof apiHandler.preError;
114
+ static set preError(preErrorHookFn: typeof apiHandler.preError);
115
+ static get postError(): typeof apiHandler.postError;
116
+ static set postError(postErrorHookFn: typeof apiHandler.postError);
117
+ constructor(basePath?: string, middlewares?: JsonRouterCallback | JsonRouterCallback[]);
118
+ get original(): ExpressRouter;
119
+ param(...args: Parameters<ExpressRouter['param']>): ReturnType<ExpressRouter['param']>;
120
+ use(...args: Parameters<ExpressRouter['use']>): ReturnType<ExpressRouter['use']>;
121
+ route(path: string): JsonRouteBuilder;
122
+ addEndpoint(method: RouteMethod, path: string): void;
123
+ getEndpoints(): Endpoint[];
124
+ normalizePath(path: string): string;
125
+ }
126
+
127
+ export { JsonRouter as default };
package/index.js ADDED
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+
25
+ // src/index.ts
26
+ var import_express_response_handler = __toESM(require("@web-ts-toolkit/express-response-handler"));
27
+ var import_success = require("@web-ts-toolkit/express-response-handler/responses/success");
28
+ var clientErrors = __toESM(require("@web-ts-toolkit/http-errors"));
29
+ var import_express = __toESM(require("express"));
30
+ var METHODS = [
31
+ "all",
32
+ "checkout",
33
+ "copy",
34
+ "delete",
35
+ "get",
36
+ "head",
37
+ "lock",
38
+ "merge",
39
+ "mkactivity",
40
+ "mkcol",
41
+ "move",
42
+ "m-search",
43
+ "notify",
44
+ "options",
45
+ "patch",
46
+ "post",
47
+ "purge",
48
+ "put",
49
+ "report",
50
+ "search",
51
+ "subscribe",
52
+ "trace",
53
+ "unlock",
54
+ "unsubscribe"
55
+ ];
56
+ var success = {
57
+ OK: import_success.OK,
58
+ Created: import_success.Created,
59
+ Accepted: import_success.Accepted,
60
+ NonAuthoritativeInfo: import_success.NonAuthoritativeInfo,
61
+ NoContent: import_success.NoContent,
62
+ ResetContent: import_success.ResetContent,
63
+ PartialContent: import_success.PartialContent,
64
+ MultiStatus: import_success.MultiStatus,
65
+ AlreadyReported: import_success.AlreadyReported,
66
+ IMUsed: import_success.IMUsed
67
+ };
68
+ var addLeadingSlash = (value) => value.startsWith("/") ? value : `/${value}`;
69
+ var normalizeBasePath = (value) => {
70
+ if (!value || value === "/") {
71
+ return "";
72
+ }
73
+ return addLeadingSlash(value).replace(/\/+$/, "");
74
+ };
75
+ var joinRoutePath = (basePath, path) => `${basePath}${addLeadingSlash(path)}`;
76
+ var toMiddlewareList = (middlewares) => {
77
+ if (!middlewares) {
78
+ return [];
79
+ }
80
+ return Array.isArray(middlewares) ? middlewares : [middlewares];
81
+ };
82
+ var JsonRouter = class {
83
+ constructor(basePath = "", middlewares) {
84
+ this.methods = [];
85
+ this.endpoints = [];
86
+ this.basePath = normalizeBasePath(basePath);
87
+ this.middlewares = toMiddlewareList(middlewares);
88
+ this._router = import_express.default.Router();
89
+ for (const method of METHODS) {
90
+ const routerMethod = this._router[method];
91
+ if (typeof routerMethod !== "function") {
92
+ continue;
93
+ }
94
+ this.methods.push(method);
95
+ Object.defineProperty(this, method, {
96
+ value: (path, ...callbacks) => {
97
+ const fullPath = joinRoutePath(this.basePath, path);
98
+ const handlers = import_express_response_handler.default.handleResponse([...this.middlewares, ...callbacks]);
99
+ routerMethod.call(this._router, fullPath, handlers);
100
+ this.addEndpoint(method, fullPath);
101
+ return this;
102
+ },
103
+ enumerable: false,
104
+ writable: false,
105
+ configurable: false
106
+ });
107
+ }
108
+ }
109
+ static {
110
+ this.clientErrors = clientErrors;
111
+ }
112
+ static {
113
+ this.success = success;
114
+ }
115
+ static {
116
+ this.HttpResponse = import_express_response_handler.default.HttpResponse;
117
+ }
118
+ static get errorMessageProvider() {
119
+ return import_express_response_handler.default.errorMessageProvider;
120
+ }
121
+ static set errorMessageProvider(customErrorMessageProvider) {
122
+ import_express_response_handler.default.errorMessageProvider = customErrorMessageProvider;
123
+ }
124
+ static get preJson() {
125
+ return import_express_response_handler.default.preJson;
126
+ }
127
+ static set preJson(preJsonHookFn) {
128
+ import_express_response_handler.default.preJson = preJsonHookFn;
129
+ }
130
+ static get postJson() {
131
+ return import_express_response_handler.default.postJson;
132
+ }
133
+ static set postJson(postJsonHookFn) {
134
+ import_express_response_handler.default.postJson = postJsonHookFn;
135
+ }
136
+ static get preError() {
137
+ return import_express_response_handler.default.preError;
138
+ }
139
+ static set preError(preErrorHookFn) {
140
+ import_express_response_handler.default.preError = preErrorHookFn;
141
+ }
142
+ static get postError() {
143
+ return import_express_response_handler.default.postError;
144
+ }
145
+ static set postError(postErrorHookFn) {
146
+ import_express_response_handler.default.postError = postErrorHookFn;
147
+ }
148
+ get original() {
149
+ return this._router;
150
+ }
151
+ param(...args) {
152
+ return this._router.param(...args);
153
+ }
154
+ use(...args) {
155
+ return this._router.use(...args);
156
+ }
157
+ route(path) {
158
+ const definition = {};
159
+ for (const method of this.methods) {
160
+ Object.defineProperty(definition, method, {
161
+ value: (...callbacks) => {
162
+ this[method](path, ...callbacks);
163
+ return definition;
164
+ },
165
+ enumerable: false,
166
+ writable: false,
167
+ configurable: false
168
+ });
169
+ }
170
+ return definition;
171
+ }
172
+ addEndpoint(method, path) {
173
+ this.endpoints.push({
174
+ method: method.toUpperCase(),
175
+ path: this.normalizePath(path)
176
+ });
177
+ }
178
+ getEndpoints() {
179
+ return this.endpoints.map((endpoint) => ({ ...endpoint }));
180
+ }
181
+ normalizePath(path) {
182
+ return addLeadingSlash(path);
183
+ }
184
+ };
185
+ module.exports = JsonRouter;
package/index.mjs ADDED
@@ -0,0 +1,182 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __commonJS = (cb, mod) => function __require() {
3
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4
+ };
5
+
6
+ // src/index.ts
7
+ import apiHandler from "@web-ts-toolkit/express-response-handler";
8
+ import {
9
+ Accepted,
10
+ AlreadyReported,
11
+ Created,
12
+ IMUsed,
13
+ MultiStatus,
14
+ NoContent,
15
+ NonAuthoritativeInfo,
16
+ OK,
17
+ PartialContent,
18
+ ResetContent
19
+ } from "@web-ts-toolkit/express-response-handler/responses/success";
20
+ import * as clientErrors from "@web-ts-toolkit/http-errors";
21
+ import express from "express";
22
+ var require_index = __commonJS({
23
+ "src/index.ts"(exports, module) {
24
+ var METHODS = [
25
+ "all",
26
+ "checkout",
27
+ "copy",
28
+ "delete",
29
+ "get",
30
+ "head",
31
+ "lock",
32
+ "merge",
33
+ "mkactivity",
34
+ "mkcol",
35
+ "move",
36
+ "m-search",
37
+ "notify",
38
+ "options",
39
+ "patch",
40
+ "post",
41
+ "purge",
42
+ "put",
43
+ "report",
44
+ "search",
45
+ "subscribe",
46
+ "trace",
47
+ "unlock",
48
+ "unsubscribe"
49
+ ];
50
+ var success = {
51
+ OK,
52
+ Created,
53
+ Accepted,
54
+ NonAuthoritativeInfo,
55
+ NoContent,
56
+ ResetContent,
57
+ PartialContent,
58
+ MultiStatus,
59
+ AlreadyReported,
60
+ IMUsed
61
+ };
62
+ var addLeadingSlash = (value) => value.startsWith("/") ? value : `/${value}`;
63
+ var normalizeBasePath = (value) => {
64
+ if (!value || value === "/") {
65
+ return "";
66
+ }
67
+ return addLeadingSlash(value).replace(/\/+$/, "");
68
+ };
69
+ var joinRoutePath = (basePath, path) => `${basePath}${addLeadingSlash(path)}`;
70
+ var toMiddlewareList = (middlewares) => {
71
+ if (!middlewares) {
72
+ return [];
73
+ }
74
+ return Array.isArray(middlewares) ? middlewares : [middlewares];
75
+ };
76
+ var JsonRouter = class {
77
+ constructor(basePath = "", middlewares) {
78
+ this.methods = [];
79
+ this.endpoints = [];
80
+ this.basePath = normalizeBasePath(basePath);
81
+ this.middlewares = toMiddlewareList(middlewares);
82
+ this._router = express.Router();
83
+ for (const method of METHODS) {
84
+ const routerMethod = this._router[method];
85
+ if (typeof routerMethod !== "function") {
86
+ continue;
87
+ }
88
+ this.methods.push(method);
89
+ Object.defineProperty(this, method, {
90
+ value: (path, ...callbacks) => {
91
+ const fullPath = joinRoutePath(this.basePath, path);
92
+ const handlers = apiHandler.handleResponse([...this.middlewares, ...callbacks]);
93
+ routerMethod.call(this._router, fullPath, handlers);
94
+ this.addEndpoint(method, fullPath);
95
+ return this;
96
+ },
97
+ enumerable: false,
98
+ writable: false,
99
+ configurable: false
100
+ });
101
+ }
102
+ }
103
+ static {
104
+ this.clientErrors = clientErrors;
105
+ }
106
+ static {
107
+ this.success = success;
108
+ }
109
+ static {
110
+ this.HttpResponse = apiHandler.HttpResponse;
111
+ }
112
+ static get errorMessageProvider() {
113
+ return apiHandler.errorMessageProvider;
114
+ }
115
+ static set errorMessageProvider(customErrorMessageProvider) {
116
+ apiHandler.errorMessageProvider = customErrorMessageProvider;
117
+ }
118
+ static get preJson() {
119
+ return apiHandler.preJson;
120
+ }
121
+ static set preJson(preJsonHookFn) {
122
+ apiHandler.preJson = preJsonHookFn;
123
+ }
124
+ static get postJson() {
125
+ return apiHandler.postJson;
126
+ }
127
+ static set postJson(postJsonHookFn) {
128
+ apiHandler.postJson = postJsonHookFn;
129
+ }
130
+ static get preError() {
131
+ return apiHandler.preError;
132
+ }
133
+ static set preError(preErrorHookFn) {
134
+ apiHandler.preError = preErrorHookFn;
135
+ }
136
+ static get postError() {
137
+ return apiHandler.postError;
138
+ }
139
+ static set postError(postErrorHookFn) {
140
+ apiHandler.postError = postErrorHookFn;
141
+ }
142
+ get original() {
143
+ return this._router;
144
+ }
145
+ param(...args) {
146
+ return this._router.param(...args);
147
+ }
148
+ use(...args) {
149
+ return this._router.use(...args);
150
+ }
151
+ route(path) {
152
+ const definition = {};
153
+ for (const method of this.methods) {
154
+ Object.defineProperty(definition, method, {
155
+ value: (...callbacks) => {
156
+ this[method](path, ...callbacks);
157
+ return definition;
158
+ },
159
+ enumerable: false,
160
+ writable: false,
161
+ configurable: false
162
+ });
163
+ }
164
+ return definition;
165
+ }
166
+ addEndpoint(method, path) {
167
+ this.endpoints.push({
168
+ method: method.toUpperCase(),
169
+ path: this.normalizePath(path)
170
+ });
171
+ }
172
+ getEndpoints() {
173
+ return this.endpoints.map((endpoint) => ({ ...endpoint }));
174
+ }
175
+ normalizePath(path) {
176
+ return addLeadingSlash(path);
177
+ }
178
+ };
179
+ module.exports = JsonRouter;
180
+ }
181
+ });
182
+ export default require_index();
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@web-ts-toolkit/express-json-router",
3
+ "description": "Express router wrapper for JSON responses",
4
+ "version": "0.1.0",
5
+ "keywords": [
6
+ "express",
7
+ "api",
8
+ "json",
9
+ "router"
10
+ ],
11
+ "main": "./index.js",
12
+ "module": "./index.mjs",
13
+ "types": "./index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./index.d.ts",
17
+ "import": "./index.mjs",
18
+ "require": "./index.js",
19
+ "default": "./index.js"
20
+ }
21
+ },
22
+ "dependencies": {
23
+ "@web-ts-toolkit/express-response-handler": "0.1.0",
24
+ "@web-ts-toolkit/http-errors": "0.1.0",
25
+ "express": "^5.2.1"
26
+ },
27
+ "author": "Junmin Dev",
28
+ "bugs": {
29
+ "url": "https://github.com/egose/web-ts-toolkit/issues"
30
+ },
31
+ "engines": {
32
+ "node": ">=20"
33
+ },
34
+ "license": "Apache-2.0",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/egose/web-ts-toolkit.git",
38
+ "directory": "packages/express-json-router"
39
+ }
40
+ }