@fjell/express-router 4.4.4 → 4.4.6

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/src/ItemRouter.ts DELETED
@@ -1,352 +0,0 @@
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 { NotFoundError, Operations } from "@fjell/lib";
13
- import deepmerge from "deepmerge";
14
- import { Request, Response, Router } from "express";
15
- import LibLogger from "./logger";
16
-
17
- export type ItemRouterOptions = Record<string, never>;
18
-
19
- export class ItemRouter<
20
- S extends string,
21
- L1 extends string = never,
22
- L2 extends string = never,
23
- L3 extends string = never,
24
- L4 extends string = never,
25
- L5 extends string = never
26
- > {
27
-
28
- protected lib: Operations<Item<S, L1, L2, L3, L4, L5>, S, L1, L2, L3, L4, L5>;
29
- private keyType: S;
30
- protected options: ItemRouterOptions;
31
- private childRouters: Record<string, Router> = {};
32
- private logger;
33
-
34
- constructor(
35
- lib: Operations<Item<S, L1, L2, L3, L4, L5>, S, L1, L2, L3, L4, L5>,
36
- keyType: S,
37
- options: ItemRouterOptions = {}
38
- ) {
39
- this.lib = lib;
40
- this.keyType = keyType;
41
- this.options = options;
42
- this.logger = LibLogger.get("ItemRouter", keyType);
43
- }
44
-
45
- public getPkType = (): S => {
46
- return this.keyType;
47
- }
48
-
49
- protected getPkParam = (): string => {
50
- return `${this.getPkType()}Pk`;
51
- }
52
-
53
- protected getLk(res: Response): LocKey<S> {
54
- return { kt: this.keyType, lk: res.locals[this.getPkParam()] };
55
- }
56
-
57
- // this is meant to be consumed by children routers
58
- public getLKA(res: Response): LocKeyArray<S, L1, L2, L3, L4> {
59
- return [this.getLk(res)] as LocKeyArray<S, L1, L2, L3, L4>;
60
- }
61
-
62
- public getPk(res: Response): PriKey<S> {
63
- return cPK<S>(res.locals[this.getPkParam()], this.getPkType());
64
- }
65
-
66
- // Unless this is a contained router, the locations will always be an empty array.
67
- /* eslint-disable */
68
- protected getLocations(res: Response): LocKeyArray<L1, L2, L3, L4, L5> | [] {
69
- throw new Error('Method not implemented in an abstract router');
70
- }
71
- /* eslint-enable */
72
-
73
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
74
- protected getIk(res: Response): PriKey<S> | ComKey<S, L1, L2, L3, L4, L5> {
75
- throw new Error('Method not implemented in an abstract router');
76
- }
77
-
78
- protected postAllAction = async (req: Request, res: Response) => {
79
- this.logger.default('Posting All Action', { query: req?.query, params: req?.params, locals: res?.locals });
80
- const allActionKey = req.path.substring(req.path.lastIndexOf('/') + 1);
81
- if (!this.lib.allActions) {
82
- this.logger.error('Item Actions are not configured');
83
- res.status(500).json({ error: 'Item Actions are not configured' });
84
- return;
85
- }
86
- const allAction = this.lib.allActions[allActionKey];
87
- if (!allAction) {
88
- this.logger.error('All Action is not configured', { allActionKey });
89
- res.status(500).json({ error: 'Item Action is not configured' });
90
- return;
91
- }
92
- try {
93
- res.json(await this.lib.allAction(allActionKey, req.body));
94
- } catch (err: any) {
95
- this.logger.error('Error in All Action', { message: err?.message, stack: err?.stack });
96
- res.status(500).json(err);
97
- }
98
- }
99
-
100
- protected getAllFacet = async (req: Request, res: Response) => {
101
- this.logger.default('Getting All Facet', { query: req?.query, params: req?.params, locals: res?.locals });
102
- const facetKey = req.path.substring(req.path.lastIndexOf('/') + 1);
103
- if (!this.lib.allFacets) {
104
- this.logger.error('Item Facets are not configured');
105
- res.status(500).json({ error: 'Item Facets are not configured' });
106
- return;
107
- }
108
- const facet = this.lib.allFacets[facetKey];
109
- if (!facet) {
110
- this.logger.error('Item Facet is not configured', { facetKey });
111
- res.status(500).json({ error: 'Item Facet is not configured' });
112
- return;
113
- }
114
- try {
115
- const combinedQueryParams = { ...req.query, ...req.params } as Record<string, string | number | boolean | Date | Array<string | number | boolean | Date>>;
116
- res.json(await this.lib.allFacet(facetKey, combinedQueryParams));
117
- } catch (err: any) {
118
- this.logger.error('Error in All Facet', { message: err?.message, stack: err?.stack });
119
- res.status(500).json(err);
120
- }
121
- }
122
-
123
- protected postItemAction = async (req: Request, res: Response) => {
124
- this.logger.default('Getting Item', { query: req?.query, params: req?.params, locals: res?.locals });
125
- const ik = this.getIk(res);
126
- const actionKey = req.path.substring(req.path.lastIndexOf('/') + 1);
127
- if (!this.lib.actions) {
128
- this.logger.error('Item Actions are not configured');
129
- res.status(500).json({ error: 'Item Actions are not configured' });
130
- return;
131
- }
132
- const action = this.lib.actions[actionKey];
133
- if (!action) {
134
- this.logger.error('Item Action is not configured', { actionKey });
135
- res.status(500).json({ error: 'Item Action is not configured' });
136
- return;
137
- }
138
- try {
139
- res.json(await this.lib.action(ik, actionKey, req.body));
140
- } catch (err: any) {
141
- this.logger.error('Error in Item Action', { message: err?.message, stack: err?.stack });
142
- res.status(500).json(err);
143
- }
144
- }
145
-
146
- protected getItemFacet = async (req: Request, res: Response) => {
147
- this.logger.default('Getting Item', { query: req?.query, params: req?.params, locals: res?.locals });
148
- const ik = this.getIk(res);
149
- const facetKey = req.path.substring(req.path.lastIndexOf('/') + 1);
150
- if (!this.lib.facets) {
151
- this.logger.error('Item Facets are not configured');
152
- res.status(500).json({ error: 'Item Facets are not configured' });
153
- return;
154
- }
155
- const facet = this.lib.facets[facetKey];
156
- if (!facet) {
157
- this.logger.error('Item Facet is not configured', { facetKey });
158
- res.status(500).json({ error: 'Item Facet is not configured' });
159
- return;
160
- }
161
- try {
162
- const combinedQueryParams = { ...req.query, ...req.params } as Record<string, string | number | boolean | Date | Array<string | number | boolean | Date>>;
163
- res.json(await this.lib.facet(ik, facetKey, combinedQueryParams));
164
- } catch (err: any) {
165
- this.logger.error('Error in Item Facet', { message: err?.message, stack: err?.stack });
166
- res.status(500).json(err);
167
- }
168
- }
169
-
170
- private configure = (router: Router) => {
171
- this.logger.default('Configuring Router', { pkType: this.getPkType() });
172
- router.get('/', this.findItems);
173
- router.post('/', this.createItem);
174
-
175
- this.logger.debug('All Actions supplied to Router', { allActions: this.lib.allActions });
176
- if (this.lib.allActions) {
177
- Object.keys(this.lib.allActions).forEach((actionKey) => {
178
- this.logger.default('Configuring All Action', { actionKey });
179
- // TODO: Ok, this is a bit of a hack, but we need to customize the types of the request handlers
180
- router.post(`/${actionKey}`, this.postAllAction);
181
- });
182
- }
183
-
184
- this.logger.debug('All Facets supplied to Router', { allFacets: this.lib.allFacets });
185
- if (this.lib.allFacets) {
186
- Object.keys(this.lib.allFacets).forEach((facetKey) => {
187
- this.logger.default('Configuring All Facet', { facetKey });
188
- // TODO: Ok, this is a bit of a hack, but we need to customize the types of the request handlers
189
- router.get(`/${facetKey}`, this.getAllFacet);
190
- });
191
- }
192
-
193
- const itemRouter = Router();
194
- itemRouter.get('/', this.getItem);
195
- itemRouter.put('/', this.updateItem);
196
- itemRouter.delete('/', this.deleteItem);
197
-
198
- this.logger.debug('Item Actions supplied to Router', { itemActions: this.lib.actions });
199
- if (this.lib.actions) {
200
- Object.keys(this.lib.actions).forEach((actionKey) => {
201
- this.logger.default('Configuring Item Action', { actionKey });
202
- // TODO: Ok, this is a bit of a hack, but we need to customize the types of the request handlers
203
- itemRouter.post(`/${actionKey}`, this.postItemAction)
204
- });
205
- }
206
-
207
- this.logger.debug('Item Facets supplied to Router', { itemFacets: this.lib.facets });
208
- if (this.lib.facets) {
209
- Object.keys(this.lib.facets).forEach((facetKey) => {
210
- this.logger.default('Configuring Item Facet', { facetKey });
211
- // TODO: Ok, this is a bit of a hack, but we need to customize the types of the request handlers
212
- itemRouter.get(`/${facetKey}`, this.getItemFacet)
213
- });
214
- }
215
-
216
- this.logger.default('Configuring Item Operations under PK Param', { pkParam: this.getPkParam() });
217
- router.use(`/:${this.getPkParam()}`, this.validatePrimaryKeyValue, itemRouter);
218
-
219
- if (this.childRouters) {
220
- this.configureChildRouters(itemRouter, this.childRouters);
221
- }
222
- return router;
223
- }
224
-
225
- private validatePrimaryKeyValue = (req: Request, res: Response, next: any) => {
226
- const pkParamValue = req.params[this.getPkParam()];
227
- if (this.validatePKParam(pkParamValue)) {
228
- res.locals[this.getPkParam()] = pkParamValue;
229
- next();
230
- } else {
231
- this.logger.error('Invalid Primary Key', { pkParamValue, path: req?.path });
232
- res.status(500).json({ error: 'Invalid Primary Key', path: req?.path });
233
- }
234
- }
235
-
236
- private configureChildRouters = (router: Router, childRouters: Record<string, Router>) => {
237
- for (const path in childRouters) {
238
- this.logger.default('Configuring Child Router at Path', { path });
239
-
240
- router.use(`/${path}`, childRouters[path]);
241
- }
242
- return router;
243
- }
244
-
245
- public addChildRouter = (path: string, router: Router) => {
246
- this.childRouters[path] = router;
247
- }
248
-
249
- /* istanbul ignore next */
250
- public getRouter(): Router {
251
- const router = Router();
252
- this.configure(router);
253
- return router;
254
- }
255
-
256
- /* istanbul ignore next */
257
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
258
- protected createItem = async (req: Request, res: Response): Promise<void> => {
259
- throw new Error('Method not implemented in an abstract router');
260
- };
261
-
262
- // TODO: Probably a better way to do this, but this postCreate hook only needs the item.
263
- /* istanbul ignore next */
264
- public postCreateItem = async (item: Item<S, L1, L2, L3, L4, L5>): Promise<Item<S, L1, L2, L3, L4, L5>> => {
265
- this.logger.default('Post Create Item', { item });
266
- return item;
267
- };
268
-
269
- protected deleteItem = async (req: Request, res: Response): Promise<void> => {
270
- this.logger.default('Deleting Item', { query: req.query, params: req.params, locals: res.locals });
271
- const ik = this.getIk(res);
272
- const removedItem = await this.lib.remove(ik);
273
- const item = validatePK(removedItem, this.getPkType());
274
- res.json(item);
275
- };
276
-
277
- /* eslint-disable */
278
- /* istanbul ignore next */
279
- protected findItems = async (req: Request, res: Response): Promise<void> => {
280
- throw new Error('Method not implemented in an abstract router');
281
- };
282
- /* eslint-enable */
283
-
284
- protected getItem = async (req: Request, res: Response) => {
285
- this.logger.default('Getting Item', { query: req.query, params: req.params, locals: res.locals });
286
- const ik = this.getIk(res);
287
- try {
288
- // TODO: What error does validate PK throw, when can that fail?
289
- const item = validatePK(await this.lib.get(ik), this.getPkType());
290
- res.json(item);
291
- } catch (err: any) {
292
- if (err instanceof NotFoundError) {
293
- this.logger.error('Item Not Found', { ik, message: err?.message, stack: err?.stack });
294
- res.status(404).json({
295
- ik,
296
- message: "Item Not Found",
297
- });
298
- } else {
299
- this.logger.error('General Error', { ik, message: err?.message, stack: err?.stack });
300
- res.status(500).json({
301
- ik,
302
- message: "General Error",
303
- });
304
- }
305
- }
306
- }
307
-
308
- protected updateItem = async (req: Request, res: Response) => {
309
- this.logger.default('Updating Item',
310
- { body: req?.body, query: req?.query, params: req?.params, locals: res?.locals });
311
- const ik = this.getIk(res);
312
- const itemToUpdate = this.convertDates(req.body as ItemProperties<S, L1, L2, L3, L4, L5>);
313
- const retItem = validatePK(await this.lib.update(ik, itemToUpdate), this.getPkType());
314
- res.json(retItem);
315
- };
316
-
317
- public convertDates = (item: Item<S, L1, L2, L3, L4, L5> | ItemProperties<S, L1, L2, L3, L4, L5>):
318
- Item<S, L1, L2, L3, L4, L5> | ItemProperties<S, L1, L2, L3, L4, L5> => {
319
- const events = item.events as Record<string, ItemEvent>;
320
- this.logger.default('Converting Dates', { item });
321
- if (events) {
322
- Object.keys(events).forEach((key: string) => {
323
- Object.assign(events, {
324
- [key]: deepmerge(events[key], { at: events[key].at ? new Date(events[key].at) : null })
325
- });
326
- });
327
- }
328
- Object.assign(item, { events });
329
- return item;
330
- };
331
-
332
- // TODO: Maybe just simplify this and require that everything is a UUID?
333
- /**
334
- * This method might be an annoyance, but we need to capture a few cases where someone passes
335
- * a PK parameter that has an odd string in it.
336
- *
337
- * @param pkParamValue The value of the primary key parameter
338
- * @returns if the value is valid.
339
- */
340
- protected validatePKParam = (pkParamValue: string): boolean => {
341
- let validPkParam = true;
342
- if (pkParamValue.length <= 0) {
343
- this.logger.error('Primary Key is an Empty String', { pkParamValue });
344
- validPkParam = false;
345
- } else if (pkParamValue === 'undefined') {
346
- this.logger.error('Primary Key is the string \'undefined\'', { pkParamValue });
347
- validPkParam = false;
348
- }
349
- return validPkParam;
350
- }
351
-
352
- }
@@ -1,63 +0,0 @@
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 as any, 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
- res.json(item);
31
- };
32
-
33
- protected findItems = async (req: Request, res: Response) => {
34
- logger.default('Finding Items', { query: req.query, params: req.params, locals: res.locals });
35
-
36
- let items: Item<S>[] = [];
37
-
38
- const query: ParsedQuery = req.query as unknown as ParsedQuery;
39
- const finder = query['finder'] as string;
40
- const finderParams = query['finderParams'] as string;
41
- const one = query['one'] as string;
42
-
43
- if (finder) {
44
- // If finder is defined? Call a finder.
45
- logger.default('Finding Items with a finder', { finder, finderParams, one });
46
-
47
- if (one === 'true') {
48
- const item = await (this.lib as any).findOne(finder, JSON.parse(finderParams));
49
- items = item ? [item] : [];
50
- } else {
51
- items = await this.lib.find(finder, JSON.parse(finderParams));
52
- }
53
- } else {
54
- logger.default('Finding Items with a query', { query: req.query });
55
- // TODO: This is once of the more important places to perform some validaation and feedback
56
- const itemQuery: ItemQuery = paramsToQuery(req.query as QueryParams);
57
- items = await this.lib.all(itemQuery);
58
- }
59
-
60
- res.json(items.map((item: Item<S>) => validatePK(item, this.getPkType())));
61
- };
62
-
63
- }
package/src/index.ts DELETED
@@ -1,3 +0,0 @@
1
- export * from "./ItemRouter";
2
- export * from "./CItemRouter";
3
- export * from "./PItemRouter";
package/src/logger.ts DELETED
@@ -1,5 +0,0 @@
1
- import Logging from '@fjell/logging';
2
-
3
- const LibLogger = Logging.getLogger('@fjell/express-router');
4
-
5
- export default LibLogger;