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