/
helpers.ts
443 lines (388 loc) · 18.3 KB
/
helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import { RequestMethod, ValidationPipe } from '@nestjs/common';
import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
import { isNil, isObject } from '@nestjs/common/utils/shared.utils';
import {
PATH_METADATA,
METHOD_METADATA,
INTERCEPTORS_METADATA,
ROUTE_ARGS_METADATA,
PARAMTYPES_METADATA,
CUSTOM_ROUTE_AGRS_METADATA,
} from '@nestjs/common/constants';
import { CrudActions, CrudValidate } from '../enums';
import { CrudOptions, RoutesOptions } from '../interfaces';
import { BaseRouteName } from '../types';
import {
ACTION_NAME_METADATA,
OVERRIDE_METHOD_METADATA,
PARSED_BODY_METADATA,
CRUD_OPTIONS_METADATA,
} from '../constants';
import { swagger, hasValidator, hasTypeorm } from '../utils';
export function setRoute(path: string, method: RequestMethod, func: Function) {
Reflect.defineMetadata(PATH_METADATA, path, func);
Reflect.defineMetadata(METHOD_METADATA, method, func);
}
export function setParamTypes(args: any[], prototype: any, name: string) {
Reflect.defineMetadata(PARAMTYPES_METADATA, args, prototype, name);
}
export function setRouteArgs(metadata: any, target: object, name: string) {
Reflect.defineMetadata(ROUTE_ARGS_METADATA, metadata, target, name);
}
export function setInterceptors(interceptors: any[], func: Function) {
Reflect.defineMetadata(INTERCEPTORS_METADATA, interceptors, func);
}
export function setAction(action: CrudActions, func: Function) {
Reflect.defineMetadata(ACTION_NAME_METADATA, action, func);
}
export function setParsedBody(meta, func: Function) {
Reflect.defineMetadata(PARSED_BODY_METADATA, meta, func);
}
export function setCrudOptionsMeta(crudOptions: CrudOptions, target: any) {
Reflect.defineMetadata(CRUD_OPTIONS_METADATA, crudOptions, target);
}
export function setSwaggerOkResponseMeta(meta: any, func: Function) {
if (swagger) {
/* istanbul ignore next line */
Reflect.defineMetadata(swagger.DECORATORS.API_RESPONSE, meta, func);
}
}
export function setSwaggerOperationMeta(meta: any, func: Function) {
if (swagger) {
/* istanbul ignore next line */
Reflect.defineMetadata(swagger.DECORATORS.API_OPERATION, meta, func);
}
}
export function setSwaggerParamsMeta(meta: any, func: Function) {
if (swagger) {
/* istanbul ignore next line */
Reflect.defineMetadata(swagger.DECORATORS.API_PARAMETERS, meta, func);
}
}
export function setSwaggerOkResponse(func: Function, dto: any, isArray?: boolean) {
if (swagger) {
/* istanbul ignore next line */
const metadata = getSwaggeOkResponse(func);
const groupedMetadata = {
[200]: {
type: dto,
isArray,
description: '',
},
};
/* istanbul ignore next line */
setSwaggerOkResponseMeta({ ...metadata, ...groupedMetadata }, func);
}
}
export function setSwaggerOperation(func: Function, summary: string) {
if (swagger) {
/* istanbul ignore next line */
const metadata = getSwaggerOperation(func);
/* istanbul ignore next line */
setSwaggerOperationMeta(Object.assign(metadata, { summary }), func);
}
}
export function setSwaggerParams(func: Function, crudOptions: CrudOptions) {
if (swagger) {
/* istanbul ignore next line */
const metadata = getSwaggerParams(func);
/* istanbul ignore next line */
const params = Object.keys(crudOptions.params).map((key) => ({
name: key,
required: true,
in: 'path',
type: crudOptions.params[key] === 'number' ? Number : String,
}));
/* istanbul ignore next line */
setSwaggerParamsMeta([...metadata, ...params], func);
}
}
export function setSwaggerQueryGetOne(func: Function) {
if (swagger) {
/* istanbul ignore next line */
const metadata = getSwaggerParams(func);
const params = [
{
name: 'fields',
description: `<h4>Selects fields that should be returned in the reponse body.</h4><i>Syntax:</i> <strong>?fields=field1,field2,...</strong> <br/><i>Example:</i> <strong>?fields=email,name</strong>`,
required: false,
in: 'query',
type: String,
},
{
name: 'join',
description: `<h4>Receive joined relational objects in GET result (with all or selected fields).</h4><i>Syntax:</i><ul><li><strong>?join=relation</strong></li><li><strong>?join=relation||field1,field2,...</strong></li><li><strong>?join=relation1||field11,field12,...&join=relation1.nested||field21,field22,...&join=...</strong></li></ul><br/><i>Examples:</i></i><ul><li><strong>?join=profile</strong></li><li><strong>?join=profile||firstName,email</strong></li><li><strong>?join=profile||firstName,email&join=notifications||content&join=tasks</strong></li><li><strong>?join=relation1&join=relation1.nested&join=relation1.nested.deepnested</strong></li></ul><strong><i>Notice:</i></strong> <code>id</code> field always persists in relational objects. To use nested relations, the parent level MUST be set before the child level like example above.`,
required: false,
in: 'query',
type: String,
},
{
name: 'cache',
description: `<h4>Reset cache (if was enabled) and receive entities from the DB.</h4><i>Usage:</i> <strong>?cache=0</strong>`,
required: false,
in: 'query',
type: Number,
},
];
/* istanbul ignore next line */
setSwaggerParamsMeta([...metadata, ...params], func);
}
}
export function setSwaggerQueryGetMany(func: Function, name: string) {
if (swagger) {
/* istanbul ignore next line */
const metadata = getSwaggerParams(func);
const params = [
{
name: 'fields',
description: `<h4>Selects fields that should be returned in the reponse body.</h4><i>Syntax:</i> <strong>?fields=field1,field2,...</strong> <br/><i>Example:</i> <strong>?fields=email,name</strong>`,
required: false,
in: 'query',
type: String,
},
{
name: 'filter',
description: `<h4>Adds fields request condition (multiple conditions) to the request.</h4><i>Syntax:</i> <strong>?filter=field||condition||value</strong><br/><i>Examples:</i> <ul><li><strong>?filter=name||eq||batman</strong></li><li><strong>?filter=isVillain||eq||false&filter=city||eq||Arkham</strong> (multiple filters are treated as a combination of AND type of conditions)</li><li><strong>?filter=shots||in||12,26</strong> (some conditions accept multiple values separated by commas)</li><li><strong>?filter=power||isnull</strong> (some conditions don't accept value)</li></ul><br/>Filter Conditions:<ul><li><strong><code>eq</code></strong> (<code>=</code>, equal)</li><li><strong><code>ne</code></strong> (<code>!=</code>, not equal)</li><li><strong><code>gt</code></strong> (<code>></code>, greater than)</li><li><strong><code>lt</code></strong> (<code><</code>, lower that)</li><li><strong><code>gte</code></strong> (<code>>=</code>, greater than or equal)</li><li><strong><code>lte</code></strong> (<code><=</code>, lower than or equal)</li><li><strong><code>starts</code></strong> (<code>LIKE val%</code>, starts with)</li><li><strong><code>ends</code></strong> (<code>LIKE %val</code>, ends with)</li><li><strong><code>cont</code></strong> (<code>LIKE %val%</code>, contains)</li><li><strong><code>excl</code></strong> (<code>NOT LIKE %val%</code>, not contains)</li><li><strong><code>in</code></strong> (<code>IN</code>, in range, <strong><em>accepts multiple values</em></strong>)</li><li><strong><code>notin</code></strong> (<code>NOT IN</code>, not in range, <strong><em>accepts multiple values</em></strong>)</li><li><strong><code>isnull</code></strong> (<code>IS NULL</code>, is NULL, <strong><em>doesn't accept value</em></strong>)</li><li><strong><code>notnull</code></strong> (<code>IS NOT NULL</code>, not NULL, <strong><em>doesn't accept value</em></strong>)</li><li><strong><code>between</code></strong> (<code>BETWEEN</code>, between, <strong><em>accepts two values</em></strong>)</li></ul>`,
required: false,
in: 'query',
type: String,
},
{
name: 'or',
description: `<h4>Adds <code>OR</code> conditions to the request.</h4><i>Syntax:</i> <strong>?or=field||condition||value</strong><br/>It uses the same conditions as the filter parameter<br/><i>Rules and <i>Examples:</i></i><ul><li>If there is only <strong>one</strong> <code>or</code> present (without <code>filter</code>) then it will be interpreted as simple filter:</li><ul><li><strong>?or=name||eq||batman</strong></li></ul></ul><ul><li>If there are <strong>multiple</strong> <code>or</code> present (without <code>filter</code>) then it will be interpreted as a compination of <code>OR</code> conditions, as follows:<br><code>WHERE {or} OR {or} OR ...</code></li><ul><li><strong>?or=name||eq||batman&or=name||eq||joker</strong></li></ul></ul><ul><li>If there are <strong>one</strong> <code>or</code> and <strong>one</strong> <code>filter</code> then it will be interpreted as <code>OR</code> condition, as follows:<br><code>WHERE {filter} OR {or}</code></li><ul><li><strong>?filter=name||eq||batman&or=name||eq||joker</strong></li></ul></ul><ul><li>If present <strong>both</strong> <code>or</code> and <code>filter</code> in any amount (<strong>one</strong> or <strong>miltiple</strong> each) then both interpreted as a combitation of <code>AND</code> conditions and compared with each other by <code>OR</code> condition, as follows:<br><code>WHERE ({filter} AND {filter} AND ...) OR ({or} AND {or} AND ...)</code></li><ul><li><strong>?filter=type||eq||hero&filter=status||eq||alive&or=type||eq||villain&or=status||eq||dead</strong></li></ul></ul>`,
required: false,
in: 'query',
type: String,
},
{
name: 'sort',
description: `<h4>Adds sort by field (by multiple fields) and order to query result.</h4><i>Syntax:</i> <strong>?sort=field,ASC|DESC</strong><br/><i>Examples:</i></i><ul><li><strong>?sort=name,ASC</strong></li><li><strong>?sort=name,ASC&sort=id,DESC</strong></li></ul>`,
required: false,
in: 'query',
type: String,
},
{
name: 'join',
description: `<h4>Receive joined relational objects in GET result (with all or selected fields).</h4><i>Syntax:</i><ul><li><strong>?join=relation</strong></li><li><strong>?join=relation||field1,field2,...</strong></li><li><strong>?join=relation1||field11,field12,...&join=relation1.nested||field21,field22,...&join=...</strong></li></ul><br/><i>Examples:</i></i><ul><li><strong>?join=profile</strong></li><li><strong>?join=profile||firstName,email</strong></li><li><strong>?join=profile||firstName,email&join=notifications||content&join=tasks</strong></li><li><strong>?join=relation1&join=relation1.nested&join=relation1.nested.deepnested</strong></li></ul><strong><i>Notice:</i></strong> <code>id</code> field always persists in relational objects. To use nested relations, the parent level MUST be set before the child level like example above.`,
required: false,
in: 'query',
type: String,
},
{
name: 'limit',
description: `<h4>Receive <code>N</code> amount of entities.</h4><i>Syntax:</i> <strong>?limit=number</strong><br/><i>Example:</i> <strong>?limit=10</strong>`,
required: false,
in: 'query',
type: Number,
},
{
name: 'offset',
description: `<h4>Offset <code>N</code> amount of entities.</h4><i>Syntax:</i> <strong>?offset=number</strong><br/><i>Example:</i> <strong>?offset=10</strong>`,
required: false,
in: 'query',
type: Number,
},
{
name: 'page',
description: `<h4>Receive a portion of <code>limit</code> (per_page) entities (alternative to <code>offset</code>). Will be applied if <code>limit</code> is set up.</h4><i>Syntax:</i> <strong>?page=number</strong><br/><i>Example:</i> <strong>?page=2</strong>`,
required: false,
in: 'query',
type: Number,
},
{
name: 'per_page',
description: `<h4>Alias for <code>limit</code></h4>`,
required: false,
in: 'query',
type: Number,
},
{
name: 'cache',
description: `<h4>Reset cache (if was enabled) and receive entities from the DB.</h4><i>Usage:</i> <strong>?cache=0</strong>`,
required: false,
in: 'query',
type: Number,
},
];
/* istanbul ignore next line */
setSwaggerParamsMeta([...metadata, ...params], func);
}
}
export function createParamMetadata(
paramtype: RouteParamtypes,
index: number,
/* istanbul ignore next line */
pipes: any[] = [],
data = undefined,
): any {
return {
[`${paramtype}:${index}`]: {
index,
pipes,
data,
},
};
}
export function createCustomRequestParamMetadata(
paramtype: string,
index: number,
pipes: any[] = [],
data = undefined,
): any {
return {
[`${paramtype}${CUSTOM_ROUTE_AGRS_METADATA}:${index}`]: {
index,
factory: (data, req) => req[paramtype],
data,
pipes,
},
};
}
export function getOverrideMetadata(func: Function): BaseRouteName {
return Reflect.getMetadata(OVERRIDE_METHOD_METADATA, func);
}
export function getInterceptors(func: Function): any[] {
return Reflect.getMetadata(INTERCEPTORS_METADATA, func);
}
export function getAction(func: Function): CrudActions {
return Reflect.getMetadata(ACTION_NAME_METADATA, func);
}
export function getParsedBody(func: Function) {
return Reflect.getMetadata(PARSED_BODY_METADATA, func);
}
export function getParamTypes(prototype: any, name: string) {
/* istanbul ignore next line */
return Reflect.getMetadata(PARAMTYPES_METADATA, prototype, name) || [];
}
export function getRouteArgs(target: object, name: string) {
/* istanbul ignore next line */
return Reflect.getMetadata(ROUTE_ARGS_METADATA, target, name) || {};
}
export function getControllerPath(target): string {
return Reflect.getMetadata(PATH_METADATA, target);
}
export function getSwaggerParams(func: Function): any[] {
if (swagger) {
/* istanbul ignore next line */
return Reflect.getMetadata(swagger.DECORATORS.API_PARAMETERS, func) || [];
}
}
export function getSwaggeOkResponse(func: Function): any {
if (swagger) {
/* istanbul ignore next line */
return Reflect.getMetadata(swagger.DECORATORS.API_RESPONSE, func) || {};
}
}
export function getSwaggerOperation(func: Function): any {
if (swagger) {
/* istanbul ignore next line */
return Reflect.getMetadata(swagger.DECORATORS.API_OPERATION, func) || {};
}
}
export function getCrudOptionsMeta(target: any): CrudOptions {
return Reflect.getMetadata(CRUD_OPTIONS_METADATA, target);
}
export function setValidationPipe(crudOptions: CrudOptions, group: CrudValidate) {
const options = crudOptions.validation || {};
return hasValidator
? new ValidationPipe({
...options,
groups: [group],
transform: false,
})
: /* istanbul ignore next line */
undefined;
}
export function enableRoute(name: BaseRouteName, crudOptions: CrudOptions) {
if (crudOptions.routes.only && crudOptions.routes.only.length) {
return crudOptions.routes.only.some((only) => only === name);
}
if (crudOptions.routes.exclude && crudOptions.routes.exclude.length) {
return !crudOptions.routes.exclude.some((exclude) => exclude === name);
}
return true;
}
export function setDefaultCrudOptions(crudOptions: CrudOptions, target: any) {
const check = (obj) => isNil(obj) || !isObject(obj) || !Object.keys(obj).length;
// set default `id` numeric slug
if (check(crudOptions.params)) {
crudOptions.params = { id: 'number' };
}
// set default routes options
if (check(crudOptions.routes)) {
crudOptions.routes = {};
}
if (check(crudOptions.routes.getManyBase)) {
crudOptions.routes.getManyBase = { interceptors: [] };
}
if (check(crudOptions.routes.getOneBase)) {
crudOptions.routes.getOneBase = { interceptors: [] };
}
if (check(crudOptions.routes.createOneBase)) {
crudOptions.routes.createOneBase = { interceptors: [] };
}
if (check(crudOptions.routes.createManyBase)) {
crudOptions.routes.createManyBase = { interceptors: [] };
}
if (check(crudOptions.routes.updateOneBase)) {
crudOptions.routes.updateOneBase = { allowParamsOverride: false, interceptors: [] };
}
if (check(crudOptions.routes.deleteOneBase)) {
crudOptions.routes.deleteOneBase = { returnDeleted: false, interceptors: [] };
}
// set metadata
setCrudOptionsMeta(crudOptions, target);
}
export function getRoutesSlugName(crudOptions: CrudOptions, path: string): string {
if (!isNil(crudOptions.params.id)) {
return 'id';
}
return Object.keys(crudOptions.params).filter((slug) => !path.includes(`:${slug}`))[0] || 'id';
}
export function getRouteInterceptors(routeOptions: any): any[] {
return Array.isArray(routeOptions.interceptors) ? routeOptions.interceptors : [];
}
export function cleanRoutesOptionsInterceptors(crudOptions: CrudOptions) {
Object.keys(<RoutesOptions>crudOptions.routes).forEach((option) => {
if (option !== 'exclude' && option !== 'only') {
crudOptions.routes[option].interceptors = [];
}
});
}
export function overrideParsedBody(target: any, baseName: BaseRouteName, name: string) {
const allowed = ['createManyBase', 'createOneBase', 'updateOneBase'] as BaseRouteName[];
const withBody = allowed.includes(baseName);
const prototype = (target as any).prototype;
const parsedBody = getParsedBody(prototype[name]);
if (withBody && parsedBody) {
const baseKey = `${RouteParamtypes.BODY}:1`;
const key = `${RouteParamtypes.BODY}:${parsedBody.index}`;
const baseRouteArgs = getRouteArgs(target, baseName);
const routeArgs = getRouteArgs(target, name);
const baseBodyArgMeta = baseRouteArgs[baseKey];
setRouteArgs(
{
...routeArgs,
[key]: {
...baseBodyArgMeta,
index: parsedBody.index,
},
},
target,
name,
);
if (baseName === 'createManyBase') {
const paramTypes = getParamTypes(prototype, name) as any[];
const metatype = paramTypes[parsedBody.index];
const types = [String, Boolean, Number, Array, Object];
/* istanbul ignore next line */
const toCopy = types.some((t) => metatype === t) || isNil(metatype);
if (toCopy) {
const baseParamTypes = getParamTypes(prototype, baseName);
const baseMetatype = baseParamTypes[1];
paramTypes.splice(parsedBody.index, 1, baseMetatype);
setParamTypes(paramTypes, prototype, name);
}
}
}
}