@fjell/express-router 4.3.1

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 2025 Fjell Project
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.
@@ -0,0 +1,14 @@
1
+ import { ComKey, Item, LocKeyArray } from "@fjell/core";
2
+ import { Request, Response } from "express";
3
+ import { ItemRouter, ItemRouterOptions } from "./ItemRouter";
4
+ import { Contained } from "@fjell/lib";
5
+ export declare class CItemRouter<T extends Item<S, L1, L2, L3, L4, L5>, S extends string, L1 extends string, L2 extends string = never, L3 extends string = never, L4 extends string = never, L5 extends string = never> extends ItemRouter<S, L1, L2, L3, L4, L5> {
6
+ private parentRoute;
7
+ constructor(lib: Contained.Operations<T, S, L1, L2, L3, L4, L5>, type: S, parentRoute: ItemRouter<L1, L2, L3, L4, L5, never>, options?: ItemRouterOptions);
8
+ hasParent(): boolean;
9
+ getIk(res: Response): ComKey<S, L1, L2, L3, L4, L5>;
10
+ getLKA(res: Response): LocKeyArray<S, L1, L2, L3, L4>;
11
+ getLocations(res: Response): LocKeyArray<L1, L2, L3, L4, L5>;
12
+ protected createItem: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
13
+ protected findItems: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
14
+ }
@@ -0,0 +1,58 @@
1
+ import { paramsToQuery, validatePK } from "@fjell/core";
2
+ import { ItemRouter } from "./ItemRouter";
3
+ import LibLogger from "./logger";
4
+ const logger = LibLogger.get('CItemRouter');
5
+ export class CItemRouter extends ItemRouter {
6
+ parentRoute;
7
+ constructor(lib, type, parentRoute, options = {}) {
8
+ super(lib, type, options);
9
+ this.parentRoute = parentRoute;
10
+ }
11
+ hasParent() {
12
+ return !!this.parentRoute;
13
+ }
14
+ getIk(res) {
15
+ const pri = this.getPk(res);
16
+ const loc = this.getLocations(res);
17
+ return { kt: pri.kt, pk: pri.pk, loc };
18
+ }
19
+ getLKA(res) {
20
+ /**
21
+ * A location key array is passed to a child router to provide contextfor the items it will
22
+ * be working with. It is always a concatenation of "My LKA" + "Parent LKA" which will
23
+ * bubble all the way up to the root Primary.
24
+ */
25
+ let lka = [this.getLk(res)];
26
+ lka = lka.concat(this.parentRoute.getLKA(res));
27
+ return lka;
28
+ }
29
+ getLocations(res) {
30
+ return this.parentRoute.getLKA(res);
31
+ }
32
+ createItem = async (req, res) => {
33
+ logger.trace('Creating Item 2', { body: req?.body, query: req?.query, params: req?.params, locals: res?.locals });
34
+ const itemToCreate = this.convertDates(req.body);
35
+ let item = validatePK(await this.lib.create(itemToCreate, { locations: this.getLocations(res) }), this.getPkType());
36
+ item = await this.postCreateItem(item);
37
+ return res.json(item);
38
+ };
39
+ /* eslint-disable */
40
+ findItems = async (req, res) => {
41
+ logger.trace('Finding Items', { query: req.query, params: req.params, locals: res.locals });
42
+ const query = req.query;
43
+ const finder = query['finder'];
44
+ const finderParams = query['finderParams'];
45
+ let items = [];
46
+ if (finder) {
47
+ // If finder is defined? Call a finder.
48
+ items = await this.lib.find(finder, JSON.parse(finderParams), this.getLocations(res));
49
+ }
50
+ else {
51
+ // TODO: This is once of the more important places to perform some validaation and feedback
52
+ const itemQuery = paramsToQuery(req.query);
53
+ items = await this.lib.all(itemQuery, this.getLocations(res));
54
+ }
55
+ return res.json(items.map((item) => validatePK(item, this.getPkType())));
56
+ };
57
+ }
58
+ //# sourceMappingURL=CItemRouter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CItemRouter.js","sourceRoot":"","sources":["../../src/CItemRouter.ts"],"names":[],"mappings":"AAAA,OAAO,EACyC,aAAa,EAAuB,UAAU,EAC7F,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,UAAU,EAAqB,MAAM,cAAc,CAAC;AAC7D,OAAO,SAAS,MAAM,UAAU,CAAC;AAGjC,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,aAAa,CAAC,CA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AAS,EAAE,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC;QAChE,CAAC;QAED,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAiC,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;IACxG,CAAC,CAAC;CAGH"}
@@ -0,0 +1,45 @@
1
+ import { ComKey, Item, ItemProperties, LocKey, LocKeyArray, PriKey } from "@fjell/core";
2
+ import { Operations } from "@fjell/lib";
3
+ import { Request, RequestHandler, Response, Router } from "express";
4
+ export type ItemRouterOptions = Record<string, never>;
5
+ export type ActionMethod = <S extends string, L1 extends string = never, L2 extends string = never, L3 extends string = never, L4 extends string = never, L5 extends string = never>(req: Request, res: Response, item: Item<S, L1, L2, L3, L4, L5>, params: any, body: any) => Promise<Item<S, L1, L2, L3, L4, L5>>;
6
+ export type AllActionMethods = Array<RequestHandler>;
7
+ export declare class ItemRouter<S extends string, L1 extends string = never, L2 extends string = never, L3 extends string = never, L4 extends string = never, L5 extends string = never> {
8
+ protected lib: Operations<Item<S, L1, L2, L3, L4, L5>, S, L1, L2, L3, L4, L5>;
9
+ private keyType;
10
+ protected options: ItemRouterOptions;
11
+ private childRouters;
12
+ private logger;
13
+ private itemActions;
14
+ constructor(lib: Operations<Item<S, L1, L2, L3, L4, L5>, S, L1, L2, L3, L4, L5>, keyType: S, options?: ItemRouterOptions);
15
+ getPkType: () => S;
16
+ protected getPkParam: () => string;
17
+ protected getLk(res: Response): LocKey<S>;
18
+ getLKA(res: Response): LocKeyArray<S, L1, L2, L3, L4>;
19
+ getPk(res: Response): PriKey<S>;
20
+ protected getLocations(res: Response): LocKeyArray<L1, L2, L3, L4, L5> | [];
21
+ protected getIk(res: Response): PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>;
22
+ protected postItemAction: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
23
+ private configure;
24
+ private validatePrimaryKeyValue;
25
+ private configureChildRouters;
26
+ addChildRouter: (path: string, router: Router) => void;
27
+ protected configureItemActions(): Record<string, ActionMethod>;
28
+ protected configureAllActions(): Record<string, AllActionMethods>;
29
+ getRouter(): import("express-serve-static-core").Router;
30
+ protected createItem: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
31
+ postCreateItem: (item: Item<S, L1, L2, L3, L4, L5>) => Promise<Item<S, L1, L2, L3, L4, L5>>;
32
+ protected deleteItem: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
33
+ protected findItems: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
34
+ protected getItem: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
35
+ protected updateItem: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
36
+ convertDates: (item: Item<S, L1, L2, L3, L4, L5> | ItemProperties<S, L1, L2, L3, L4, L5>) => Item<S, L1, L2, L3, L4, L5> | ItemProperties<S, L1, L2, L3, L4, L5>;
37
+ /**
38
+ * This method might be an annoyance, but we need to capture a few cases where someone passes
39
+ * a PK parameter that has an odd string in it.
40
+ *
41
+ * @param pkParamValue The value of the primary key parameter
42
+ * @returns if the value is valid.
43
+ */
44
+ protected validatePKParam: (pkParamValue: string) => boolean;
45
+ }
@@ -0,0 +1,208 @@
1
+ import { cPK, validatePK } from "@fjell/core";
2
+ import deepmerge from "deepmerge";
3
+ import { Router } from "express";
4
+ import LibLogger from "./logger";
5
+ export class ItemRouter {
6
+ lib;
7
+ keyType;
8
+ options;
9
+ childRouters = {};
10
+ logger;
11
+ itemActions;
12
+ constructor(lib, keyType, options = {}) {
13
+ this.lib = lib;
14
+ this.keyType = keyType;
15
+ this.options = options;
16
+ this.logger = LibLogger.get("ItemRouter", keyType);
17
+ }
18
+ getPkType = () => {
19
+ return this.keyType;
20
+ };
21
+ getPkParam = () => {
22
+ return `${this.getPkType()}Pk`;
23
+ };
24
+ getLk(res) {
25
+ return { kt: this.keyType, lk: res.locals[this.getPkParam()] };
26
+ }
27
+ // this is meant to be consumed by children routers
28
+ getLKA(res) {
29
+ return [this.getLk(res)];
30
+ }
31
+ getPk(res) {
32
+ return cPK(res.locals[this.getPkParam()], this.getPkType());
33
+ }
34
+ // Unless this is a contained router, the locations will always be an empty array.
35
+ /* eslint-disable */
36
+ getLocations(res) {
37
+ throw new Error('Method not implemented in an abstract router');
38
+ }
39
+ /* eslint-enable */
40
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
41
+ getIk(res) {
42
+ throw new Error('Method not implemented in an abstract router');
43
+ }
44
+ postItemAction = async (req, res) => {
45
+ this.logger.default('Getting Item', { query: req?.query, params: req?.params, locals: res?.locals });
46
+ const ik = this.getIk(res);
47
+ const actionKey = req.path.substring(req.path.lastIndexOf('/') + 1);
48
+ if (!this.itemActions) {
49
+ this.logger.error('Item Actions are not configured');
50
+ return res.status(500).json({ error: 'Item Actions are not configured' });
51
+ }
52
+ try {
53
+ const item = validatePK(await this.lib.get(ik), this.getPkType());
54
+ return res.json(await this.itemActions[actionKey](req, res, item, req.params, req.body));
55
+ }
56
+ catch (err) {
57
+ this.logger.error('Error in Item Action', { message: err?.message, stack: err?.stack });
58
+ return res.status(500).json(err);
59
+ }
60
+ };
61
+ configure = (router) => {
62
+ this.logger.default('Configuring Router', { pkType: this.getPkType() });
63
+ router.get('/', this.findItems);
64
+ router.post('/', this.createItem);
65
+ const allActions = this.configureAllActions();
66
+ this.logger.info('All Actions supplied to Router', { allActions });
67
+ if (allActions) {
68
+ Object.keys(allActions).forEach((actionKey) => {
69
+ this.logger.default('Configuring All Action', { actionKey });
70
+ // TODO: Ok, this is a bit of a hack, but we need to customize the types of the request handlers
71
+ router.post(`/${actionKey}`, ...allActions[actionKey]);
72
+ });
73
+ }
74
+ const itemRouter = Router();
75
+ itemRouter.get('/', this.getItem);
76
+ itemRouter.put('/', this.updateItem);
77
+ itemRouter.delete('/', this.deleteItem);
78
+ this.itemActions = this.configureItemActions();
79
+ this.logger.info('Item Actions supplied to Router', { itemActions: this.itemActions });
80
+ if (this.itemActions) {
81
+ Object.keys(this.itemActions).forEach((actionKey) => {
82
+ this.logger.default('Configuring Item Action', { actionKey });
83
+ // TODO: Ok, this is a bit of a hack, but we need to customize the types of the request handlers
84
+ itemRouter.post(`/${actionKey}`, this.postItemAction);
85
+ });
86
+ }
87
+ this.logger.default('Configuring Item Operations under PK Param', { pkParam: this.getPkParam() });
88
+ router.use(`/:${this.getPkParam()}`, this.validatePrimaryKeyValue, itemRouter);
89
+ if (this.childRouters) {
90
+ this.configureChildRouters(itemRouter, this.childRouters);
91
+ }
92
+ return router;
93
+ };
94
+ validatePrimaryKeyValue = (req, res, next) => {
95
+ const pkParamValue = req.params[this.getPkParam()];
96
+ if (this.validatePKParam(pkParamValue)) {
97
+ res.locals[this.getPkParam()] = pkParamValue;
98
+ next();
99
+ }
100
+ else {
101
+ this.logger.error('Invalid Primary Key', { pkParamValue, path: req?.path });
102
+ res.status(500).json({ error: 'Invalid Primary Key', path: req?.path });
103
+ }
104
+ };
105
+ configureChildRouters = (router, childRouters) => {
106
+ for (const path in childRouters) {
107
+ this.logger.default('Configuring Child Router at Path', { path });
108
+ router.use(`/${path}`, childRouters[path]);
109
+ }
110
+ return router;
111
+ };
112
+ addChildRouter = (path, router) => {
113
+ this.childRouters[path] = router;
114
+ };
115
+ /* istanbul ignore next */
116
+ configureItemActions() {
117
+ this.logger.info('ARouter - No Item Actions Configured');
118
+ return {};
119
+ }
120
+ /* istanbul ignore next */
121
+ configureAllActions() {
122
+ this.logger.info('ARouter - No All Actions Configured');
123
+ return {};
124
+ }
125
+ /* istanbul ignore next */
126
+ getRouter() {
127
+ const router = Router();
128
+ this.configure(router);
129
+ return router;
130
+ }
131
+ /* istanbul ignore next */
132
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
133
+ createItem = async (req, res) => {
134
+ throw new Error('Method not implemented in an abstract router');
135
+ };
136
+ // TODO: Probably a better way to do this, but this postCreate hook only needs the item.
137
+ /* istanbul ignore next */
138
+ postCreateItem = async (item) => {
139
+ this.logger.default('Post Create Item', { item });
140
+ return item;
141
+ };
142
+ deleteItem = async (req, res) => {
143
+ this.logger.default('Deleting Item', { query: req.query, params: req.params, locals: res.locals });
144
+ const ik = this.getIk(res);
145
+ const removedItem = await this.lib.remove(ik);
146
+ const item = validatePK(removedItem, this.getPkType());
147
+ return res.json(item);
148
+ };
149
+ /* eslint-disable */
150
+ /* istanbul ignore next */
151
+ findItems = async (req, res) => {
152
+ throw new Error('Method not implemented in an abstract router');
153
+ };
154
+ /* eslint-enable */
155
+ getItem = async (req, res) => {
156
+ this.logger.default('Getting Item', { query: req.query, params: req.params, locals: res.locals });
157
+ const ik = this.getIk(res);
158
+ try {
159
+ const item = validatePK(await this.lib.get(ik), this.getPkType());
160
+ return res.json(item);
161
+ }
162
+ catch (err) {
163
+ this.logger.error('Error in Get Item Returning 404', { message: err?.message, stack: err?.stack });
164
+ return res.status(404).json(err);
165
+ }
166
+ };
167
+ updateItem = async (req, res) => {
168
+ this.logger.default('Updating Item', { body: req?.body, query: req?.query, params: req?.params, locals: res?.locals });
169
+ const ik = this.getIk(res);
170
+ const itemToUpdate = this.convertDates(req.body);
171
+ const retItem = validatePK(await this.lib.update(ik, itemToUpdate), this.getPkType());
172
+ return res.json(retItem);
173
+ };
174
+ convertDates = (item) => {
175
+ const events = item.events;
176
+ this.logger.default('Converting Dates', { item });
177
+ if (events) {
178
+ Object.keys(events).forEach((key) => {
179
+ Object.assign(events, {
180
+ [key]: deepmerge(events[key], { at: events[key].at ? new Date(events[key].at) : null })
181
+ });
182
+ });
183
+ }
184
+ Object.assign(item, { events });
185
+ return item;
186
+ };
187
+ // TODO: Maybe just simplify this and require that everything is a UUID?
188
+ /**
189
+ * This method might be an annoyance, but we need to capture a few cases where someone passes
190
+ * a PK parameter that has an odd string in it.
191
+ *
192
+ * @param pkParamValue The value of the primary key parameter
193
+ * @returns if the value is valid.
194
+ */
195
+ validatePKParam = (pkParamValue) => {
196
+ let validPkParam = true;
197
+ if (pkParamValue.length <= 0) {
198
+ this.logger.error('Primary Key is an Empty String', { pkParamValue });
199
+ validPkParam = false;
200
+ }
201
+ else if (pkParamValue === 'undefined') {
202
+ this.logger.error('Primary Key is the string \'undefined\'', { pkParamValue });
203
+ validPkParam = false;
204
+ }
205
+ return validPkParam;
206
+ };
207
+ }
208
+ //# sourceMappingURL=ItemRouter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ItemRouter.js","sourceRoot":"","sources":["../../src/ItemRouter.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,GAAG,EAOH,UAAU,EACX,MAAM,aAAa,CAAC;AAErB,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAqC,MAAM,EAAE,MAAM,SAAS,CAAC;AACpE,OAAO,SAAS,MAAM,UAAU,CAAC;AAkBjC,MAAM,OAAO,UAAU;IASX,GAAG,CAAiE;IACtE,OAAO,CAAI;IACT,OAAO,CAAoB;IAC7B,YAAY,GAA2B,EAAE,CAAC;IAC1C,MAAM,CAAC;IACP,WAAW,CAA2C;IAE9D,YACE,GAAmE,EACnE,OAAU,EACV,UAA6B,EAAE;QAE/B,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IACrD,CAAC;IAEM,SAAS,GAAG,GAAM,EAAE;QACzB,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC,CAAA;IAES,UAAU,GAAG,GAAW,EAAE;QAClC,OAAO,GAAG,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC;IACjC,CAAC,CAAA;IAES,KAAK,CAAC,GAAa;QAC3B,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,E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EAAE,MAAM,EAAE,CAAC,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IAEF,wEAAwE;IACxE;;;;;;OAMG;IACO,eAAe,GAAG,CAAC,YAAoB,EAAW,EAAE;QAC5D,IAAI,YAAY,GAAG,IAAI,CAAC;QACxB,IAAI,YAAY,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;YAC7B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gCAAgC,EAAE,EAAE,YAAY,EAAE,CAAC,CAAC;YACtE,YAAY,GAAG,KAAK,CAAC;QACvB,CAAC;aAAM,IAAI,YAAY,KAAK,WAAW,EAAE,CAAC;YACxC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yCAAyC,EAAE,EAAE,YAAY,EAAE,CAAC,CAAC;YAC/E,YAAY,GAAG,KAAK,CAAC;QACvB,CAAC;QACD,OAAO,YAAY,CAAC;IACtB,CAAC,CAAA;CAEF"}
@@ -0,0 +1,10 @@
1
+ import { Item, PriKey } from "@fjell/core";
2
+ import { Primary } from "@fjell/lib";
3
+ import { ItemRouter, ItemRouterOptions } from "./ItemRouter";
4
+ import { Request, Response } from "express";
5
+ export declare class PItemRouter<T extends Item<S>, S extends string> extends ItemRouter<S> {
6
+ constructor(lib: Primary.Operations<T, S>, keyType: S, options?: ItemRouterOptions);
7
+ getIk(res: Response): PriKey<S>;
8
+ createItem: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
9
+ protected findItems: (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
10
+ }
@@ -0,0 +1,41 @@
1
+ import { paramsToQuery, validatePK } from "@fjell/core";
2
+ import { ItemRouter } from "./ItemRouter";
3
+ import LibLogger from "./logger";
4
+ const logger = LibLogger.get('PItemRouter');
5
+ export class PItemRouter extends ItemRouter {
6
+ constructor(lib, keyType, options = {}) {
7
+ super(lib, keyType, options);
8
+ }
9
+ getIk(res) {
10
+ const pri = this.getPk(res);
11
+ return pri;
12
+ }
13
+ createItem = async (req, res) => {
14
+ logger.default('Creating Item 2', { body: req.body, query: req.query, params: req.params, locals: res.locals });
15
+ const itemToCreate = this.convertDates(req.body);
16
+ let item = validatePK(await this.lib.create(itemToCreate), this.getPkType());
17
+ item = await this.postCreateItem(item);
18
+ return res.json(item);
19
+ };
20
+ /* eslint-disable */
21
+ findItems = async (req, res) => {
22
+ logger.default('Finding Items', { query: req.query, params: req.params, locals: res.locals });
23
+ let items = [];
24
+ const query = req.query;
25
+ const finder = query['finder'];
26
+ const finderParams = query['finderParams'];
27
+ if (finder) {
28
+ // If finder is defined? Call a finder.
29
+ logger.default('Finding Items with a finder', { finder, finderParams });
30
+ items = await this.lib.find(finder, JSON.parse(finderParams));
31
+ }
32
+ else {
33
+ logger.default('Finding Items with a query', { query: req.query });
34
+ // TODO: This is once of the more important places to perform some validaation and feedback
35
+ const itemQuery = paramsToQuery(req.query);
36
+ items = await this.lib.all(itemQuery);
37
+ }
38
+ return res.json(items.map((item) => validatePK(item, this.getPkType())));
39
+ };
40
+ }
41
+ //# sourceMappingURL=PItemRouter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PItemRouter.js","sourceRoot":"","sources":["../../src/PItemRouter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,aAAa,EAAuB,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9F,OAAO,EAAE,UAAU,EAAqB,MAAM,cAAc,CAAC;AAE7D,OAAO,SAAS,MAAM,UAAU,CAAC;AAEjC,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;AAM5C,MAAM,OAAO,WAAiD,SAAQ,UAAa;IAEjF,YAAY,GAA6B,EAAE,OAAU,EAAE,UAA6B,EAAE;QACpF,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC/B,CAAC;IAEM,KAAK,CAAC,GAAa;QACxB,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAc,CAAC;QAC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AAK,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC;QAChE,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,OAAO,CAAC,4BAA4B,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC;YACnE,2FAA2F;YAC3F,MAAM,SAAS,GAAc,aAAa,CAAC,GAAG,CAAC,KAAoB,CAAC,CAAC;YACrE,KAAK,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QACxC,CAAC;QAED,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAa,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;IACpF,CAAC,CAAC;CAEH"}
@@ -0,0 +1,3 @@
1
+ export * from "./ItemRouter";
2
+ export * from "./CItemRouter";
3
+ export * from "./PItemRouter";
@@ -0,0 +1,4 @@
1
+ export * from "./ItemRouter";
2
+ export * from "./CItemRouter";
3
+ export * from "./PItemRouter";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC"}
@@ -0,0 +1,2 @@
1
+ declare const LibLogger: import("@fjell/logging").Logger;
2
+ export default LibLogger;
@@ -0,0 +1,4 @@
1
+ import Logging from '@fjell/logging';
2
+ const LibLogger = Logging.getLogger('@fjellproject/express-router');
3
+ export default LibLogger;
4
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,gBAAgB,CAAC;AAErC,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,8BAA8B,CAAC,CAAC;AAEpE,eAAe,SAAS,CAAC"}
@@ -0,0 +1,70 @@
1
+ import typescriptEslint from "@typescript-eslint/eslint-plugin";
2
+ import tsParser from "@typescript-eslint/parser";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import js from "@eslint/js";
6
+ import { FlatCompat } from "@eslint/eslintrc";
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+ const compat = new FlatCompat({
11
+ baseDirectory: __dirname,
12
+ recommendedConfig: js.configs.recommended,
13
+ allConfig: js.configs.all
14
+ });
15
+
16
+ export default [{
17
+ ignores: ["**/dist", "**/node_modules"],
18
+ }, ...compat.extends("plugin:@typescript-eslint/recommended"), {
19
+ plugins: {
20
+ "@typescript-eslint": typescriptEslint,
21
+ },
22
+
23
+ languageOptions: {
24
+ parser: tsParser,
25
+ },
26
+
27
+ rules: {
28
+ "@typescript-eslint/no-unused-expressions": "off",
29
+ "no-console": 0,
30
+ "no-unused-vars": "off",
31
+
32
+ "max-len": ["error", {
33
+ code: 120,
34
+ }],
35
+
36
+ "max-depth": ["error", 4],
37
+ "max-params": ["error", 4],
38
+ "max-lines": ["error", 500],
39
+
40
+ "no-multiple-empty-lines": ["error", {
41
+ max: 1,
42
+ maxEOF: 1,
43
+ }],
44
+
45
+ "no-trailing-spaces": ["error", {
46
+ skipBlankLines: true,
47
+ }],
48
+
49
+ indent: ["error", 2, {
50
+ SwitchCase: 1,
51
+ }],
52
+
53
+ "sort-imports": ["error", {
54
+ ignoreCase: true,
55
+ ignoreDeclarationSort: true,
56
+ ignoreMemberSort: false,
57
+ memberSyntaxSortOrder: ["none", "all", "multiple", "single"],
58
+ }],
59
+
60
+ "no-var": "error",
61
+ "no-undefined": "error",
62
+ "@typescript-eslint/no-unused-vars": "error",
63
+ "@typescript-eslint/ban-ts-comment": "off",
64
+ "@typescript-eslint/no-explicit-any": "off",
65
+
66
+ "no-restricted-imports": ["error", {
67
+ patterns: ["..*", "src/*"],
68
+ }],
69
+ },
70
+ }];
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@fjell/express-router",
3
+ "version": "4.3.1",
4
+ "license": "UNLICENSED",
5
+ "description": "Express Router for Fjell",
6
+ "engines": {
7
+ "node": ">=21"
8
+ },
9
+ "main": "dist/src/index.js",
10
+ "exports": {
11
+ ".": {
12
+ "require": "./dist/src/index.js",
13
+ "import": "./dist/src/index.js",
14
+ "types": "./dist/src/index.d.ts"
15
+ }
16
+ },
17
+ "type": "module",
18
+ "scripts": {
19
+ "build": "yarn run lint && tsc && tsc-alias -p tsconfig.json",
20
+ "dev": "concurrently \"tsc -w\" \"tsc-alias -w\"",
21
+ "lint": "eslint .",
22
+ "clean": "rimraf dist",
23
+ "test": "yarn run lint && NODE_OPTIONS='--experimental-require-module' yarn run jest --coverage"
24
+ },
25
+ "dependencies": {
26
+ "@fjell/lib": "^4.3.0",
27
+ "@fjell/logging": "^4.3.4",
28
+ "@google-cloud/firestore": "^7.5.0",
29
+ "cors": "^2.8.5",
30
+ "dayjs": "^1.11.13",
31
+ "deepmerge": "^4.3.1",
32
+ "dotenv": "^16.4.7",
33
+ "express": "^4.18.2",
34
+ "multer": "^1.4.5-lts.1",
35
+ "nodemailer": "^6.10.0",
36
+ "response-time": "^2.3.3",
37
+ "specifier-resolution-node": "^1.1.4",
38
+ "supertest": "^7.0.0",
39
+ "winston": "^3.17.0"
40
+ },
41
+ "devDependencies": {
42
+ "@babel/preset-env": "^7.26.9",
43
+ "@babel/preset-react": "^7.26.3",
44
+ "@babel/preset-typescript": "^7.26.0",
45
+ "@tsconfig/recommended": "^1.0.8",
46
+ "@types/cors": "^2.8.17",
47
+ "@types/express": "^4.17.21",
48
+ "@types/jest": "^29.5.14",
49
+ "@types/multer": "^1.4.11",
50
+ "@types/node": "^20.10.4",
51
+ "@types/nodemailer": "^6.4.14",
52
+ "@types/react": "^18.3.1",
53
+ "@types/response-time": "^2.3.8",
54
+ "@typescript-eslint/eslint-plugin": "^8.24.1",
55
+ "@typescript-eslint/parser": "^8.24.1",
56
+ "concurrently": "^9.1.2",
57
+ "eslint": "^9.21.0",
58
+ "jest": "^29.7.0",
59
+ "nodemon": "^3.1.9",
60
+ "rimraf": "^6.0.1",
61
+ "ts-jest": "^29.2.5",
62
+ "ts-node": "^10.9.2",
63
+ "tsc-alias": "^1.8.10",
64
+ "typescript": "^5.7.3"
65
+ },
66
+ "packageManager": "yarn@4.6.0",
67
+ "repository": {
68
+ "type": "git",
69
+ "url": "git+https://github.com/getfjell/express-router.git"
70
+ }
71
+ }
@@ -0,0 +1,95 @@
1
+ import {
2
+ ComKey, Item, ItemQuery, LocKey, LocKeyArray, paramsToQuery, PriKey, QueryParams, validatePK
3
+ } from "@fjell/core";
4
+ import { Request, Response } from "express";
5
+ import { ItemRouter, ItemRouterOptions } from "@/ItemRouter";
6
+ import LibLogger from "@/logger";
7
+ import { Contained } from "@fjell/lib";
8
+
9
+ const logger = LibLogger.get('CItemRouter');
10
+ interface ParsedQuery {
11
+ [key: string]: undefined | string | string[] | ParsedQuery | ParsedQuery[];
12
+ }
13
+
14
+ export class CItemRouter<
15
+ T extends Item<S, L1, L2, L3, L4, L5>,
16
+ S extends string,
17
+ L1 extends string,
18
+ L2 extends string = never,
19
+ L3 extends string = never,
20
+ L4 extends string = never,
21
+ L5 extends string = never
22
+ > extends ItemRouter<S, L1, L2, L3, L4, L5> {
23
+
24
+ private parentRoute: ItemRouter<L1, L2, L3, L4, L5, never>;
25
+
26
+ constructor(
27
+ lib: Contained.Operations<T, S, L1, L2, L3, L4, L5>,
28
+ type: S,
29
+ parentRoute: ItemRouter<L1, L2, L3, L4, L5, never>,
30
+ options: ItemRouterOptions = {},
31
+ ) {
32
+ super(lib, type, options);
33
+ this.parentRoute = parentRoute;
34
+ }
35
+
36
+ public hasParent(): boolean {
37
+ return !!this.parentRoute;
38
+ }
39
+
40
+ public getIk(res: Response): ComKey<S, L1, L2, L3, L4, L5> {
41
+ const pri = this.getPk(res) as PriKey<S>;
42
+ const loc = this.getLocations(res) as LocKeyArray<L1, L2, L3, L4, L5>;
43
+ return { kt: pri.kt, pk: pri.pk, loc }
44
+ }
45
+
46
+ public getLKA(res: Response): LocKeyArray<S, L1, L2, L3, L4> {
47
+ /**
48
+ * A location key array is passed to a child router to provide contextfor the items it will
49
+ * be working with. It is always a concatenation of "My LKA" + "Parent LKA" which will
50
+ * bubble all the way up to the root Primary.
51
+ */
52
+ let lka: LocKey<S | L1 | L2 | L3 | L4>[] = [this.getLk(res)];
53
+ lka = lka.concat(this.parentRoute.getLKA(res) as LocKey<S | L1 | L2 | L3 | L4>[]);
54
+ return lka as LocKeyArray<S, L1, L2, L3, L4>;
55
+ }
56
+
57
+ public getLocations(res: Response): LocKeyArray<L1, L2, L3, L4, L5> {
58
+ return this.parentRoute.getLKA(res) as LocKeyArray<L1, L2, L3, L4, L5>;
59
+ }
60
+
61
+ protected createItem = async (req: Request, res: Response) => {
62
+ logger.trace('Creating Item 2',
63
+ { body: req?.body, query: req?.query, params: req?.params, locals: res?.locals });
64
+ const itemToCreate = this.convertDates(req.body as Item<S, L1, L2, L3, L4, L5>);
65
+ let item =
66
+ validatePK(await this.lib.create(
67
+ itemToCreate, { locations: this.getLocations(res) }), this.getPkType()) as Item<S, L1, L2, L3, L4, L5>;
68
+ item = await this.postCreateItem(item);
69
+ return res.json(item);
70
+ };
71
+
72
+ /* eslint-disable */
73
+ protected findItems = async (req: Request, res: Response) => {
74
+ logger.trace('Finding Items', { query: req.query, params: req.params, locals: res.locals });
75
+
76
+ const query: ParsedQuery = req.query as unknown as ParsedQuery;
77
+ const finder = query['finder'] as string;
78
+ const finderParams = query['finderParams'] as string;
79
+
80
+ let items: Item<S, L1, L2, L3, L4, L5>[] = [];
81
+
82
+ if( finder ) {
83
+ // If finder is defined? Call a finder.
84
+ items = await this.lib.find(finder, JSON.parse(finderParams), this.getLocations(res));
85
+ } else {
86
+ // TODO: This is once of the more important places to perform some validaation and feedback
87
+ const itemQuery: ItemQuery = paramsToQuery(req.query as QueryParams);
88
+ items = await this.lib.all(itemQuery, this.getLocations(res));
89
+ }
90
+
91
+ return res.json(items.map((item: Item<S, L1, L2, L3, L4, L5>) => validatePK(item, this.getPkType())));
92
+ };
93
+ /* eslint-enable */
94
+
95
+ }
@@ -0,0 +1,277 @@
1
+ import {
2
+ ComKey,
3
+ cPK,
4
+ Item,
5
+ ItemEvent,
6
+ ItemProperties,
7
+ LocKey,
8
+ LocKeyArray,
9
+ PriKey,
10
+ validatePK
11
+ } from "@fjell/core";
12
+ import { Operations } from "@fjell/lib";
13
+ import deepmerge from "deepmerge";
14
+ import { Request, RequestHandler, Response, Router } from "express";
15
+ import LibLogger from "./logger";
16
+
17
+ export type ItemRouterOptions = Record<string, never>;
18
+
19
+ // TODO: body is in the request, it's not needed in the parameters
20
+ export type ActionMethod = <
21
+ S extends string,
22
+ L1 extends string = never,
23
+ L2 extends string = never,
24
+ L3 extends string = never,
25
+ L4 extends string = never,
26
+ L5 extends string = never
27
+ >(req: Request, res: Response, item: Item<S, L1, L2, L3, L4, L5>, params: any, body: any) =>
28
+ Promise<Item<S, L1, L2, L3, L4, L5>>;
29
+
30
+ // TODO: body is in the request, it's not needed in the parameters
31
+ export type AllActionMethods = Array<RequestHandler>;
32
+
33
+ export class ItemRouter<
34
+ S extends string,
35
+ L1 extends string = never,
36
+ L2 extends string = never,
37
+ L3 extends string = never,
38
+ L4 extends string = never,
39
+ L5 extends string = never
40
+ > {
41
+
42
+ protected lib: Operations<Item<S, L1, L2, L3, L4, L5>, S, L1, L2, L3, L4, L5>;
43
+ private keyType: S;
44
+ protected options: ItemRouterOptions;
45
+ private childRouters: Record<string, Router> = {};
46
+ private logger;
47
+ private itemActions: Record<string, ActionMethod> | undefined;
48
+
49
+ constructor(
50
+ lib: Operations<Item<S, L1, L2, L3, L4, L5>, S, L1, L2, L3, L4, L5>,
51
+ keyType: S,
52
+ options: ItemRouterOptions = {}
53
+ ) {
54
+ this.lib = lib;
55
+ this.keyType = keyType;
56
+ this.options = options;
57
+ this.logger = LibLogger.get("ItemRouter", keyType);
58
+ }
59
+
60
+ public getPkType = (): S => {
61
+ return this.keyType;
62
+ }
63
+
64
+ protected getPkParam = (): string => {
65
+ return `${this.getPkType()}Pk`;
66
+ }
67
+
68
+ protected getLk(res: Response): LocKey<S> {
69
+ return { kt: this.keyType, lk: res.locals[this.getPkParam()] };
70
+ }
71
+
72
+ // this is meant to be consumed by children routers
73
+ public getLKA(res: Response): LocKeyArray<S, L1, L2, L3, L4> {
74
+ return [this.getLk(res)] as LocKeyArray<S, L1, L2, L3, L4>;
75
+ }
76
+
77
+ public getPk(res: Response): PriKey<S> {
78
+ return cPK<S>(res.locals[this.getPkParam()], this.getPkType());
79
+ }
80
+
81
+ // Unless this is a contained router, the locations will always be an empty array.
82
+ /* eslint-disable */
83
+ protected getLocations(res: Response): LocKeyArray<L1, L2, L3, L4, L5> | [] {
84
+ throw new Error('Method not implemented in an abstract router');
85
+ }
86
+ /* eslint-enable */
87
+
88
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
89
+ protected getIk(res: Response): PriKey<S> | ComKey<S, L1, L2, L3, L4, L5> {
90
+ throw new Error('Method not implemented in an abstract router');
91
+ }
92
+
93
+ protected postItemAction = async (req: Request, res: Response) => {
94
+ this.logger.default('Getting Item', { query: req?.query, params: req?.params, locals: res?.locals });
95
+ const ik = this.getIk(res);
96
+ const actionKey = req.path.substring(req.path.lastIndexOf('/') + 1);
97
+ if (!this.itemActions) {
98
+ this.logger.error('Item Actions are not configured');
99
+ return res.status(500).json({ error: 'Item Actions are not configured' });
100
+ }
101
+ try {
102
+ const item =
103
+ validatePK(await this.lib.get(ik), this.getPkType()) as Item<S, L1, L2, L3, L4, L5>;
104
+ return res.json(await this.itemActions[actionKey](req, res, item, req.params, req.body));
105
+ } catch (err: any) {
106
+ this.logger.error('Error in Item Action', { message: err?.message, stack: err?.stack });
107
+ return res.status(500).json(err);
108
+ }
109
+ }
110
+
111
+ private configure = (router: Router) => {
112
+ this.logger.default('Configuring Router', { pkType: this.getPkType() });
113
+ router.get('/', this.findItems);
114
+ router.post('/', this.createItem);
115
+
116
+ const allActions = this.configureAllActions();
117
+ this.logger.info('All Actions supplied to Router', { allActions });
118
+ if (allActions) {
119
+ Object.keys(allActions).forEach((actionKey) => {
120
+ this.logger.default('Configuring All Action', { actionKey });
121
+ // TODO: Ok, this is a bit of a hack, but we need to customize the types of the request handlers
122
+ router.post(`/${actionKey}`, ...allActions[actionKey]);
123
+ });
124
+ }
125
+
126
+ const itemRouter = Router();
127
+ itemRouter.get('/', this.getItem);
128
+ itemRouter.put('/', this.updateItem);
129
+ itemRouter.delete('/', this.deleteItem);
130
+
131
+ this.itemActions = this.configureItemActions();
132
+ this.logger.info('Item Actions supplied to Router', { itemActions:this.itemActions });
133
+ if (this.itemActions) {
134
+ Object.keys(this.itemActions).forEach((actionKey) => {
135
+ this.logger.default('Configuring Item Action', { actionKey });
136
+ // TODO: Ok, this is a bit of a hack, but we need to customize the types of the request handlers
137
+ itemRouter.post(`/${actionKey}`, this.postItemAction)
138
+ });
139
+ }
140
+
141
+ this.logger.default('Configuring Item Operations under PK Param', { pkParam: this.getPkParam() });
142
+ router.use(`/:${this.getPkParam()}`, this.validatePrimaryKeyValue, itemRouter);
143
+
144
+ if (this.childRouters) {
145
+ this.configureChildRouters(itemRouter, this.childRouters);
146
+ }
147
+ return router;
148
+ }
149
+
150
+ private validatePrimaryKeyValue = (req: Request, res: Response, next: any) => {
151
+ const pkParamValue = req.params[this.getPkParam()];
152
+ if (this.validatePKParam(pkParamValue)) {
153
+ res.locals[this.getPkParam()] = pkParamValue;
154
+ next();
155
+ } else {
156
+ this.logger.error('Invalid Primary Key', { pkParamValue, path: req?.path });
157
+ res.status(500).json({ error: 'Invalid Primary Key', path: req?.path });
158
+ }
159
+ }
160
+
161
+ private configureChildRouters = (router: Router, childRouters: Record<string, Router>) => {
162
+ for (const path in childRouters) {
163
+ this.logger.default('Configuring Child Router at Path', { path });
164
+
165
+ router.use(`/${path}`, childRouters[path]);
166
+ }
167
+ return router;
168
+ }
169
+
170
+ public addChildRouter = (path: string, router: Router) => {
171
+ this.childRouters[path] = router;
172
+ }
173
+
174
+ /* istanbul ignore next */
175
+ protected configureItemActions(): Record<string, ActionMethod> {
176
+ this.logger.info('ARouter - No Item Actions Configured');
177
+ return {};
178
+ }
179
+
180
+ /* istanbul ignore next */
181
+ protected configureAllActions(): Record<string, AllActionMethods> {
182
+ this.logger.info('ARouter - No All Actions Configured');
183
+ return {};
184
+ }
185
+
186
+ /* istanbul ignore next */
187
+ public getRouter() {
188
+ const router = Router();
189
+ this.configure(router);
190
+ return router;
191
+ }
192
+
193
+ /* istanbul ignore next */
194
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
195
+ protected createItem = async (req: Request, res: Response): Promise<Response<any, Record<string, any>>> => {
196
+ throw new Error('Method not implemented in an abstract router');
197
+ };
198
+
199
+ // TODO: Probably a better way to do this, but this postCreate hook only needs the item.
200
+ /* istanbul ignore next */
201
+ public postCreateItem = async (item: Item<S, L1, L2, L3, L4, L5>): Promise<Item<S, L1, L2, L3, L4, L5>> => {
202
+ this.logger.default('Post Create Item', { item });
203
+ return item;
204
+ };
205
+
206
+ protected deleteItem = async (req: Request, res: Response): Promise<Response<any, Record<string, any>>> => {
207
+ this.logger.default('Deleting Item', { query: req.query, params: req.params, locals: res.locals });
208
+ const ik = this.getIk(res);
209
+ const removedItem = await this.lib.remove(ik);
210
+ const item = validatePK(removedItem, this.getPkType());
211
+ return res.json(item);
212
+ };
213
+
214
+ /* eslint-disable */
215
+ /* istanbul ignore next */
216
+ protected findItems = async (req: Request, res: Response): Promise<Response<any, Record<string, any>>> => {
217
+ throw new Error('Method not implemented in an abstract router');
218
+ };
219
+ /* eslint-enable */
220
+
221
+ protected getItem = async (req: Request, res: Response) => {
222
+ this.logger.default('Getting Item', { query: req.query, params: req.params, locals: res.locals });
223
+ const ik = this.getIk(res);
224
+ try {
225
+ const item = validatePK(await this.lib.get(ik), this.getPkType());
226
+ return res.json(item);
227
+ } catch (err: any) {
228
+ this.logger.error('Error in Get Item Returning 404', { message: err?.message, stack: err?.stack });
229
+ return res.status(404).json(err);
230
+ }
231
+ }
232
+
233
+ protected updateItem = async (req: Request, res: Response) => {
234
+ this.logger.default('Updating Item',
235
+ { body: req?.body, query: req?.query, params: req?.params, locals: res?.locals });
236
+ const ik = this.getIk(res);
237
+ const itemToUpdate = this.convertDates(req.body as ItemProperties<S, L1, L2, L3, L4, L5>);
238
+ const retItem = validatePK(await this.lib.update(ik, itemToUpdate), this.getPkType());
239
+ return res.json(retItem);
240
+ };
241
+
242
+ public convertDates = (item: Item<S, L1, L2, L3, L4, L5> | ItemProperties<S, L1, L2, L3, L4, L5>):
243
+ Item<S, L1, L2, L3, L4, L5> | ItemProperties<S, L1, L2, L3, L4, L5> => {
244
+ const events = item.events as Record<string, ItemEvent>;
245
+ this.logger.default('Converting Dates', { item });
246
+ if (events) {
247
+ Object.keys(events).forEach((key: string) => {
248
+ Object.assign(events, {
249
+ [key]: deepmerge(events[key], { at: events[key].at ? new Date(events[key].at) : null })
250
+ });
251
+ });
252
+ }
253
+ Object.assign(item, { events });
254
+ return item;
255
+ };
256
+
257
+ // TODO: Maybe just simplify this and require that everything is a UUID?
258
+ /**
259
+ * This method might be an annoyance, but we need to capture a few cases where someone passes
260
+ * a PK parameter that has an odd string in it.
261
+ *
262
+ * @param pkParamValue The value of the primary key parameter
263
+ * @returns if the value is valid.
264
+ */
265
+ protected validatePKParam = (pkParamValue: string): boolean => {
266
+ let validPkParam = true;
267
+ if (pkParamValue.length <= 0) {
268
+ this.logger.error('Primary Key is an Empty String', { pkParamValue });
269
+ validPkParam = false;
270
+ } else if (pkParamValue === 'undefined') {
271
+ this.logger.error('Primary Key is the string \'undefined\'', { pkParamValue });
272
+ validPkParam = false;
273
+ }
274
+ return validPkParam;
275
+ }
276
+
277
+ }
@@ -0,0 +1,57 @@
1
+ import { Item, ItemQuery, paramsToQuery, PriKey, QueryParams, validatePK } from "@fjell/core";
2
+ import { Primary } from "@fjell/lib";
3
+ import { ItemRouter, ItemRouterOptions } from "@/ItemRouter";
4
+ import { Request, Response } from "express";
5
+ import LibLogger from "@/logger";
6
+
7
+ const logger = LibLogger.get('PItemRouter');
8
+
9
+ interface ParsedQuery {
10
+ [key: string]: undefined | string | string[] | ParsedQuery | ParsedQuery[];
11
+ }
12
+
13
+ export class PItemRouter<T extends Item<S>, S extends string> extends ItemRouter<S> {
14
+
15
+ constructor(lib: Primary.Operations<T, S>, keyType: S, options: ItemRouterOptions = {}) {
16
+ super(lib, keyType, options);
17
+ }
18
+
19
+ public getIk(res: Response): PriKey<S> {
20
+ const pri = this.getPk(res) as PriKey<S>;
21
+ return pri
22
+ }
23
+
24
+ public createItem = async (req: Request, res: Response) => {
25
+ logger.default('Creating Item 2', { body: req.body, query: req.query, params: req.params, locals: res.locals });
26
+ const itemToCreate = this.convertDates(req.body as Item<S>);
27
+ let item =
28
+ validatePK(await this.lib.create(itemToCreate), this.getPkType()) as Item<S>;
29
+ item = await this.postCreateItem(item);
30
+ return res.json(item);
31
+ };
32
+
33
+ /* eslint-disable */
34
+ protected findItems = async (req: Request, res: Response) => {
35
+ logger.default('Finding Items', { query: req.query, params: req.params, locals: res.locals });
36
+
37
+ let items: Item<S>[] = [];
38
+
39
+ const query: ParsedQuery = req.query as unknown as ParsedQuery;
40
+ const finder = query['finder'] as string;
41
+ const finderParams = query['finderParams'] as string;
42
+
43
+ if( finder ) {
44
+ // If finder is defined? Call a finder.
45
+ logger.default('Finding Items with a finder', { finder, finderParams });
46
+ items = await this.lib.find(finder, JSON.parse(finderParams));
47
+ } else {
48
+ logger.default('Finding Items with a query', { query: req.query });
49
+ // TODO: This is once of the more important places to perform some validaation and feedback
50
+ const itemQuery: ItemQuery = paramsToQuery(req.query as QueryParams);
51
+ items = await this.lib.all(itemQuery);
52
+ }
53
+
54
+ return res.json(items.map((item: Item<S>) => validatePK(item, this.getPkType())));
55
+ };
56
+ /* eslint-enable */
57
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./ItemRouter";
2
+ export * from "./CItemRouter";
3
+ export * from "./PItemRouter";
package/src/logger.ts ADDED
@@ -0,0 +1,5 @@
1
+ import Logging from '@fjell/logging';
2
+
3
+ const LibLogger = Logging.getLogger('@fjellproject/express-router');
4
+
5
+ export default LibLogger;