crud-query-parser 0.1.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +154 -35
- package/dist/adapters/array/index.d.mts +90 -0
- package/dist/adapters/array/index.d.ts +90 -0
- package/dist/adapters/array/index.js +2 -0
- package/dist/adapters/array/index.js.map +1 -0
- package/dist/adapters/array/index.mjs +2 -0
- package/dist/adapters/array/index.mjs.map +1 -0
- package/dist/adapters/dynamodb/index.d.mts +239 -0
- package/dist/adapters/dynamodb/index.d.ts +239 -0
- package/dist/adapters/dynamodb/index.js +2 -0
- package/dist/adapters/dynamodb/index.js.map +1 -0
- package/dist/adapters/dynamodb/index.mjs +2 -0
- package/dist/adapters/dynamodb/index.mjs.map +1 -0
- package/dist/adapters/mongodb/index.d.mts +163 -0
- package/dist/adapters/mongodb/index.d.ts +163 -0
- package/dist/adapters/mongodb/index.js +2 -0
- package/dist/adapters/mongodb/index.js.map +1 -0
- package/dist/adapters/mongodb/index.mjs +2 -0
- package/dist/adapters/mongodb/index.mjs.map +1 -0
- package/dist/adapters/sequelize/index.d.mts +190 -0
- package/dist/adapters/sequelize/index.d.ts +190 -0
- package/dist/adapters/sequelize/index.js +2 -0
- package/dist/adapters/sequelize/index.js.map +1 -0
- package/dist/adapters/sequelize/index.mjs +2 -0
- package/dist/adapters/sequelize/index.mjs.map +1 -0
- package/dist/adapters/typeorm/index.d.mts +4 -4
- package/dist/adapters/typeorm/index.d.ts +4 -4
- package/dist/adapters/typeorm/index.js +1 -1
- package/dist/adapters/typeorm/index.js.map +1 -1
- package/dist/adapters/typeorm/index.mjs +1 -1
- package/dist/adapters/typeorm/index.mjs.map +1 -1
- package/dist/crud-request-9u0s-DnI.d.mts +193 -0
- package/dist/crud-request-9u0s-DnI.d.ts +193 -0
- package/dist/{crud-request-where.builder-B5241Aht.d.ts → crud-request-where.builder-Cq0DKiuS.d.ts} +1 -1
- package/dist/{crud-request-where.builder-BwWLx0Bh.d.mts → crud-request-where.builder-D_V4JtjY.d.mts} +1 -1
- package/dist/filters/index.d.mts +1 -1
- package/dist/filters/index.d.ts +1 -1
- package/dist/filters/index.js +1 -1
- package/dist/filters/index.js.map +1 -1
- package/dist/filters/index.mjs +1 -1
- package/dist/filters/index.mjs.map +1 -1
- package/dist/helpers/express/index.d.mts +30 -0
- package/dist/helpers/express/index.d.ts +30 -0
- package/dist/helpers/express/index.js +2 -0
- package/dist/helpers/express/index.js.map +1 -0
- package/dist/helpers/express/index.mjs +2 -0
- package/dist/helpers/express/index.mjs.map +1 -0
- package/dist/helpers/nestjs/index.d.mts +4 -3
- package/dist/helpers/nestjs/index.d.ts +4 -3
- package/dist/helpers/nestjs/index.js +1 -1
- package/dist/helpers/nestjs/index.js.map +1 -1
- package/dist/helpers/nestjs/index.mjs +1 -1
- package/dist/helpers/nestjs/index.mjs.map +1 -1
- package/dist/index.d.mts +12 -4
- package/dist/index.d.ts +12 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/parsers/crud/index.d.mts +44 -5
- package/dist/parsers/crud/index.d.ts +44 -5
- package/dist/parsers/crud/index.js +1 -1
- package/dist/parsers/crud/index.js.map +1 -1
- package/dist/parsers/crud/index.mjs +1 -1
- package/dist/parsers/crud/index.mjs.map +1 -1
- package/dist/{query-adapter-CEcyFcWr.d.ts → query-adapter-CZ_oD6Ui.d.ts} +3 -3
- package/dist/{query-adapter-CeTK3yxp.d.mts → query-adapter-HqVhBKtl.d.mts} +3 -3
- package/dist/{request-parser-BxVulcsX.d.ts → request-parser-C-cBNlki.d.ts} +4 -4
- package/dist/{request-parser-BMkszvGr.d.mts → request-parser-DYVGG34f.d.mts} +4 -4
- package/package.json +101 -4
- package/dist/crud-request-x16CuDRF.d.mts +0 -84
- package/dist/crud-request-x16CuDRF.d.ts +0 -84
@@ -0,0 +1,193 @@
|
|
1
|
+
/**
|
2
|
+
* Field path
|
3
|
+
*
|
4
|
+
* For post.category.name, this would be ["post", "category", "name"]
|
5
|
+
*/
|
6
|
+
type FieldPath = string[];
|
7
|
+
|
8
|
+
type CrudRequestWhere = CrudRequestWhereAND | CrudRequestWhereOR | CrudRequestWhereField;
|
9
|
+
interface CrudRequestWhereAND {
|
10
|
+
field?: never;
|
11
|
+
or?: never;
|
12
|
+
and: CrudRequestWhere[];
|
13
|
+
}
|
14
|
+
interface CrudRequestWhereOR {
|
15
|
+
field?: never;
|
16
|
+
or: CrudRequestWhere[];
|
17
|
+
and?: never;
|
18
|
+
}
|
19
|
+
interface CrudRequestWhereField {
|
20
|
+
/**
|
21
|
+
* Field path
|
22
|
+
*
|
23
|
+
* For post.category.name, this would be ["post", "category", "name"]
|
24
|
+
*/
|
25
|
+
field: FieldPath;
|
26
|
+
/**
|
27
|
+
* The operator of the comparison
|
28
|
+
*/
|
29
|
+
operator: CrudRequestWhereOperator;
|
30
|
+
/**
|
31
|
+
* The value to compare
|
32
|
+
*/
|
33
|
+
value: CrudRequestWhereValueType | CrudRequestWhereValueType[];
|
34
|
+
or?: never;
|
35
|
+
and?: never;
|
36
|
+
}
|
37
|
+
type CrudRequestWhereValueType = string | number | boolean | Date | null | undefined;
|
38
|
+
declare enum CrudRequestWhereOperator {
|
39
|
+
/**
|
40
|
+
* Equals (`==`) (accepts string, number, boolean and Date)
|
41
|
+
*/
|
42
|
+
EQ = "eq",
|
43
|
+
/**
|
44
|
+
* Not Equals (`!=`) (accepts string, number, boolean and Date)
|
45
|
+
*/
|
46
|
+
NEQ = "neq",
|
47
|
+
/**
|
48
|
+
* Greater than (`>`) (accepts string, number, boolean and Date)
|
49
|
+
*/
|
50
|
+
GT = "gt",
|
51
|
+
/**
|
52
|
+
* Greater than or equal (`>=`) (accepts string, number, boolean and Date)
|
53
|
+
*/
|
54
|
+
GTE = "gte",
|
55
|
+
/**
|
56
|
+
* Less than (`<`) (accepts string, number, boolean and Date)
|
57
|
+
*/
|
58
|
+
LT = "lt",
|
59
|
+
/**
|
60
|
+
* Less than or equal (`<=`) (accepts string, number, boolean and Date)
|
61
|
+
*/
|
62
|
+
LTE = "lte",
|
63
|
+
/**
|
64
|
+
* Starts with (accepts string)
|
65
|
+
*/
|
66
|
+
STARTS = "starts",
|
67
|
+
/**
|
68
|
+
* Ends with (accepts string)
|
69
|
+
*/
|
70
|
+
ENDS = "ends",
|
71
|
+
/**
|
72
|
+
* Contains (accepts string)
|
73
|
+
*/
|
74
|
+
CONTAINS = "contains",
|
75
|
+
/**
|
76
|
+
* Not contains (accepts string)
|
77
|
+
*/
|
78
|
+
NOT_CONTAINS = "not_contains",
|
79
|
+
/**
|
80
|
+
* Includes (accepts an array of string, number, boolean or Date)
|
81
|
+
*/
|
82
|
+
IN = "in",
|
83
|
+
/**
|
84
|
+
* Not includes (accepts an array of string, number, boolean or Date)
|
85
|
+
*/
|
86
|
+
NOT_IN = "not_in",
|
87
|
+
/**
|
88
|
+
* Between (`value >= arr[0] && value <= arr[1]`) (accepts an array of two values being string, number or Date)
|
89
|
+
*/
|
90
|
+
BETWEEN = "between",
|
91
|
+
/**
|
92
|
+
* Is `null` (the value must be `null`, `undefined` or `true`)
|
93
|
+
*/
|
94
|
+
IS_NULL = "is_null",
|
95
|
+
/**
|
96
|
+
* Is not `null` (the value must be `null`, `undefined` or `true`)
|
97
|
+
*/
|
98
|
+
NOT_NULL = "not_null",
|
99
|
+
/**
|
100
|
+
* Equals (case-insensitive) (`==`) (accepts string)
|
101
|
+
*/
|
102
|
+
EQ_LOWER = "eq_lower",
|
103
|
+
/**
|
104
|
+
* Not equals (case-insensitive) (`!=`) (accepts string)
|
105
|
+
*/
|
106
|
+
NEQ_LOWER = "neq_lower",
|
107
|
+
/**
|
108
|
+
* Starts with (case-insensitive) (accepts string)
|
109
|
+
*/
|
110
|
+
STARTS_LOWER = "starts_lower",
|
111
|
+
/**
|
112
|
+
* Ends with (case-insensitive) (accepts string)
|
113
|
+
*/
|
114
|
+
ENDS_LOWER = "ends_lower",
|
115
|
+
/**
|
116
|
+
* Contains (case-insensitive) (accepts string)
|
117
|
+
*/
|
118
|
+
CONTAINS_LOWER = "contains_lower",
|
119
|
+
/**
|
120
|
+
* Not contains (case-insensitive) (accepts string)
|
121
|
+
*/
|
122
|
+
NOT_CONTAINS_LOWER = "not_contains_lower",
|
123
|
+
/**
|
124
|
+
* Includes (case-insensitive) (accepts an array of strings)
|
125
|
+
*/
|
126
|
+
IN_LOWER = "in_lower",
|
127
|
+
/**
|
128
|
+
* Not includes (case-insensitive) (accepts an array of strings)
|
129
|
+
*/
|
130
|
+
NOT_IN_LOWER = "not_in_lower"
|
131
|
+
}
|
132
|
+
|
133
|
+
interface CrudRequestFields {
|
134
|
+
/**
|
135
|
+
* The field path.
|
136
|
+
*
|
137
|
+
* For post.category.name, this would be ["post", "category", "name"]
|
138
|
+
*/
|
139
|
+
field: FieldPath;
|
140
|
+
}
|
141
|
+
interface CrudRequestRelation extends CrudRequestFields {
|
142
|
+
/**
|
143
|
+
* The joining alias only used by adapters that do support it.
|
144
|
+
*/
|
145
|
+
alias?: string;
|
146
|
+
}
|
147
|
+
interface CrudRequestOrder extends CrudRequestFields {
|
148
|
+
/**
|
149
|
+
* The sort direction.
|
150
|
+
*
|
151
|
+
* "ASC" for ascending and "DESC" for descending.
|
152
|
+
*/
|
153
|
+
order: 'ASC' | 'DESC';
|
154
|
+
}
|
155
|
+
type ParsedRequestSelect = CrudRequestFields[];
|
156
|
+
interface CrudRequest {
|
157
|
+
/**
|
158
|
+
* The list of fields to return.
|
159
|
+
*
|
160
|
+
* In case the list is empty, it will return all fields.
|
161
|
+
*/
|
162
|
+
select: ParsedRequestSelect;
|
163
|
+
/**
|
164
|
+
* The list of relations to join
|
165
|
+
*/
|
166
|
+
relations: CrudRequestRelation[];
|
167
|
+
/**
|
168
|
+
* The fields that the result should be sorted by
|
169
|
+
*/
|
170
|
+
order: CrudRequestOrder[];
|
171
|
+
/**
|
172
|
+
* The conditions that will filter the results
|
173
|
+
*/
|
174
|
+
where: CrudRequestWhere;
|
175
|
+
/**
|
176
|
+
* The maximum amount of entities to return
|
177
|
+
*/
|
178
|
+
limit?: number;
|
179
|
+
/**
|
180
|
+
* The amount of entities to offset, starting at 0.
|
181
|
+
*
|
182
|
+
* In case this property is set, the `page` property will be ignored.
|
183
|
+
*/
|
184
|
+
offset?: number;
|
185
|
+
/**
|
186
|
+
* The current page number, starting at 1.
|
187
|
+
*
|
188
|
+
* This property will be ignored if `offset` is defined.
|
189
|
+
*/
|
190
|
+
page?: number;
|
191
|
+
}
|
192
|
+
|
193
|
+
export { type CrudRequest as C, type FieldPath as F, type ParsedRequestSelect as P, type CrudRequestFields as a, type CrudRequestRelation as b, type CrudRequestOrder as c, type CrudRequestWhere as d, type CrudRequestWhereAND as e, type CrudRequestWhereOR as f, type CrudRequestWhereField as g, type CrudRequestWhereValueType as h, CrudRequestWhereOperator as i };
|
package/dist/{crud-request-where.builder-B5241Aht.d.ts → crud-request-where.builder-Cq0DKiuS.d.ts}
RENAMED
@@ -1,4 +1,4 @@
|
|
1
|
-
import { e as CrudRequestWhereAND, f as CrudRequestWhereOR, i as CrudRequestWhereOperator, h as CrudRequestWhereValueType, d as CrudRequestWhere } from './crud-request-
|
1
|
+
import { e as CrudRequestWhereAND, f as CrudRequestWhereOR, i as CrudRequestWhereOperator, h as CrudRequestWhereValueType, d as CrudRequestWhere } from './crud-request-9u0s-DnI.js';
|
2
2
|
|
3
3
|
/**
|
4
4
|
* A helper class that makes it easier to create a CrudRequestWhere
|
package/dist/{crud-request-where.builder-BwWLx0Bh.d.mts → crud-request-where.builder-D_V4JtjY.d.mts}
RENAMED
@@ -1,4 +1,4 @@
|
|
1
|
-
import { e as CrudRequestWhereAND, f as CrudRequestWhereOR, i as CrudRequestWhereOperator, h as CrudRequestWhereValueType, d as CrudRequestWhere } from './crud-request-
|
1
|
+
import { e as CrudRequestWhereAND, f as CrudRequestWhereOR, i as CrudRequestWhereOperator, h as CrudRequestWhereValueType, d as CrudRequestWhere } from './crud-request-9u0s-DnI.mjs';
|
2
2
|
|
3
3
|
/**
|
4
4
|
* A helper class that makes it easier to create a CrudRequestWhere
|
package/dist/filters/index.d.mts
CHANGED
package/dist/filters/index.d.ts
CHANGED
package/dist/filters/index.js
CHANGED
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var l=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var o=(n,e)=>l(n,"name",{value:e,configurable:!0});var R=(n,e)=>{for(var i in e)l(n,i,{get:e[i],enumerable:!0})},T=(n,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _(e))!N.call(n,r)&&r!==i&&l(n,r,{get:()=>e[r],enumerable:!(t=c(e,r))||t.enumerable});return n};var E=n=>T(l({},"__esModule",{value:!0}),n);var L={};R(L,{ensureCondition:()=>d,ensureEqCondition:()=>m,ensureLimit:()=>a,filterProperties:()=>x,filterRelations:()=>C});module.exports=E(L);function d(n,e){return n.where.and?{...n,where:{and:[
|
1
|
+
"use strict";var l=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var o=(n,e)=>l(n,"name",{value:e,configurable:!0});var R=(n,e)=>{for(var i in e)l(n,i,{get:e[i],enumerable:!0})},T=(n,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _(e))!N.call(n,r)&&r!==i&&l(n,r,{get:()=>e[r],enumerable:!(t=c(e,r))||t.enumerable});return n};var E=n=>T(l({},"__esModule",{value:!0}),n);var L={};R(L,{ensureCondition:()=>d,ensureEqCondition:()=>m,ensureLimit:()=>a,filterProperties:()=>x,filterRelations:()=>C});module.exports=E(L);function d(n,e){return n.where.and?{...n,where:{and:[e,...n.where.and]}}:{...n,where:{and:[e,n.where]}}}o(d,"ensureCondition");function m(n,e,i=[]){for(let t of Object.keys(e)){if(typeof e[t]=="object"&&!Array.isArray(e[t])){n=m(n,e[t],[...i,t]);continue}n=d(n,{field:[...i,t],operator:"eq",value:e[t]})}return n}o(m,"ensureEqCondition");function a(n,e,i){return{...n,limit:Math.min(Math.max(n.limit??e,1),i)}}o(a,"ensureLimit");function x(n,e){let i=n.select;i.length===0?i=e.map(f=>({field:f.split(".")})):i=n.select.filter(f=>e.includes(f.field.join(".")));let t=u(n.where,e)??{and:[]},r=n.order.filter(f=>e.includes(f.field.join("."))),s=n.relations.filter(f=>e.includes(f.field.join(".")));return{...n,select:i,where:t,order:r,relations:s}}o(x,"filterProperties");function u(n,e){if(n.or)return{or:n.or.map(i=>u(i,e)).filter(i=>!!i)};if(n.and)return{and:n.and.map(i=>u(i,e)).filter(i=>!!i)};if(!(n.field&&!e.includes(n.field.join("."))))return n}o(u,"filterPropertyAccessWhere");function C(n,e){let i=n.relations.filter(t=>e.includes(t.field.join(".")));return{...n,relations:i}}o(C,"filterRelations");0&&(module.exports={ensureCondition,ensureEqCondition,ensureLimit,filterProperties,filterRelations});
|
2
2
|
//# sourceMappingURL=index.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/filters/index.ts","../../src/filters/conditions/ensureCondition.ts","../../src/filters/conditions/ensureEqCondition.ts","../../src/filters/limit/ensureLimit.ts","../../src/filters/property/filterProperties.ts","../../src/filters/property/filterRelations.ts"],"sourcesContent":["\r\nexport * from './conditions/ensureCondition';\r\nexport * from './conditions/ensureEqCondition';\r\nexport * from './limit/ensureLimit';\r\nexport * from './property/filterProperties';\r\nexport * from './property/filterRelations';\r\n","import { CrudRequest } from '../../models/crud-request';\r\nimport { CrudRequestWhere } from '../../models/crud-request-where';\r\n\r\n/**\r\n * Ensures a condition is always applied to the query\r\n *\r\n * @param request The parsed request\r\n * @param condition The condition that needs to be applied\r\n */\r\nexport function ensureCondition(request: CrudRequest, condition: CrudRequestWhere): CrudRequest {\r\n // If there is already an \"AND\" condition, we'll just append to that\r\n if (request.where.and) {\r\n return {\r\n ...request,\r\n where: {\r\n and: [\r\n ...request.where.and,\r\n
|
1
|
+
{"version":3,"sources":["../../src/filters/index.ts","../../src/filters/conditions/ensureCondition.ts","../../src/filters/conditions/ensureEqCondition.ts","../../src/filters/limit/ensureLimit.ts","../../src/filters/property/filterProperties.ts","../../src/filters/property/filterRelations.ts"],"sourcesContent":["\r\nexport * from './conditions/ensureCondition';\r\nexport * from './conditions/ensureEqCondition';\r\nexport * from './limit/ensureLimit';\r\nexport * from './property/filterProperties';\r\nexport * from './property/filterRelations';\r\n","import { CrudRequest } from '../../models/crud-request';\r\nimport { CrudRequestWhere } from '../../models/crud-request-where';\r\n\r\n/**\r\n * Ensures a condition is always applied to the query\r\n *\r\n * @param request The parsed request\r\n * @param condition The condition that needs to be applied\r\n */\r\nexport function ensureCondition(request: CrudRequest, condition: CrudRequestWhere): CrudRequest {\r\n // If there is already an \"AND\" condition, we'll just append to that\r\n if (request.where.and) {\r\n return {\r\n ...request,\r\n where: {\r\n and: [\r\n condition,\r\n ...request.where.and,\r\n ]\r\n }\r\n }\r\n }\r\n\r\n return {\r\n ...request,\r\n where: {\r\n and: [\r\n condition,\r\n request.where,\r\n ],\r\n },\r\n };\r\n}\r\n","import { CrudRequest } from '../../models/crud-request';\r\nimport { ensureCondition } from './ensureCondition';\r\nimport { CrudRequestWhereOperator } from '../../models/crud-request-where';\r\n\r\n/**\r\n * Ensures a condition is always applied to the query\r\n *\r\n * @param request The parsed request\r\n * @param entity The property that need to be applied\r\n * @param basePath The field path prefix\r\n */\r\nexport function ensureEqCondition<T extends Record<string, any>>(request: CrudRequest, entity: Partial<T>, basePath: string[] = []): CrudRequest {\r\n for (const key of Object.keys(entity)) {\r\n if (typeof entity[key] === 'object' && !Array.isArray(entity[key])) {\r\n request = ensureEqCondition(request, entity[key], [...basePath, key]);\r\n continue;\r\n }\r\n\r\n request = ensureCondition(request, {\r\n field: [...basePath, key],\r\n operator: CrudRequestWhereOperator.EQ,\r\n value: entity[key],\r\n });\r\n }\r\n\r\n return request;\r\n}\r\n","import { CrudRequest } from '../../models/crud-request';\r\n\r\n/**\r\n * Ensures that the limit will be set following a maximum rule\r\n *\r\n * @param request The parsed request\r\n * @param defaultLimit The default limit number\r\n * @param maxLimit The maximum allowed limit number\r\n */\r\nexport function ensureLimit(request: CrudRequest, defaultLimit: number, maxLimit: number): CrudRequest {\r\n return {\r\n ...request,\r\n limit: Math.min(Math.max(request.limit ?? defaultLimit, 1), maxLimit),\r\n };\r\n}\r\n","import { CrudRequest } from '../../models/crud-request';\r\nimport { CrudRequestWhere } from '../../models/crud-request-where';\r\n\r\n/**\r\n * Filters access to an allowlist of properties and relations.\r\n * No selecting, filtering, sorting and joining can be done on a property that is not listed.\r\n *\r\n * @param request The parsed request\r\n * @param allowedProperties The list of properties (in case of a field path, separated by dot) that will be allowed\r\n */\r\nexport function filterProperties(\r\n request: CrudRequest,\r\n allowedProperties: string[],\r\n): CrudRequest {\r\n let select = request.select;\r\n\r\n if (select.length === 0) {\r\n select = allowedProperties.map(prop => ({ field: prop.split('.') }));\r\n } else {\r\n select = request.select.filter(item => allowedProperties.includes(item.field.join('.')));\r\n }\r\n\r\n const where = filterPropertyAccessWhere(request.where, allowedProperties) ?? { and: [] };\r\n\r\n const order = request.order.filter(item => allowedProperties.includes(item.field.join('.')));\r\n\r\n // TODO allow relations by the first part of field paths\r\n const relations = request.relations.filter(item => allowedProperties.includes(item.field.join('.')));\r\n\r\n return {\r\n ...request,\r\n select,\r\n where,\r\n order,\r\n relations,\r\n };\r\n}\r\n\r\nfunction filterPropertyAccessWhere(\r\n where: CrudRequestWhere,\r\n allowedProperties: string[],\r\n): CrudRequestWhere | undefined {\r\n if (where.or) {\r\n return {\r\n or: where.or\r\n .map(w => filterPropertyAccessWhere(w, allowedProperties))\r\n .filter(w => !!w),\r\n };\r\n }\r\n\r\n if (where.and) {\r\n return {\r\n and: where.and\r\n .map(w => filterPropertyAccessWhere(w, allowedProperties))\r\n .filter(w => !!w),\r\n };\r\n }\r\n\r\n if (where.field) {\r\n if (!allowedProperties.includes(where.field.join('.')))\r\n return undefined;\r\n }\r\n\r\n return where;\r\n}\r\n\r\n","import { CrudRequest } from '../../models/crud-request';\r\n\r\n/**\r\n * Filters access to an allowlist of relations.\r\n *\r\n * @param request The parsed request\r\n * @param allowedRelations The list of relations (in case of a field path, separated by dot) that will be allowed\r\n */\r\nexport function filterRelations(\r\n request: CrudRequest,\r\n allowedRelations: string[],\r\n): CrudRequest {\r\n const relations = request.relations.filter(item => allowedRelations.includes(item.field.join('.')));\r\n\r\n return {\r\n ...request,\r\n relations,\r\n };\r\n}\r\n"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,qBAAAC,EAAA,oBAAAC,IAAA,eAAAC,EAAAP,GCSO,SAASQ,EAAgBC,EAAsBC,EAA0C,CAE9F,OAAID,EAAQ,MAAM,IACT,CACL,GAAGA,EACH,MAAO,CACL,IAAK,CACHC,EACA,GAAGD,EAAQ,MAAM,GACnB,CACF,CACF,EAGK,CACL,GAAGA,EACH,MAAO,CACL,IAAK,CACHC,EACAD,EAAQ,KACV,CACF,CACF,CACF,CAvBgBE,EAAAH,EAAA,mBCET,SAASI,EAAiDC,EAAsBC,EAAoBC,EAAqB,CAAC,EAAgB,CAC/I,QAAWC,KAAO,OAAO,KAAKF,CAAM,EAAG,CACrC,GAAI,OAAOA,EAAOE,CAAG,GAAM,UAAY,CAAC,MAAM,QAAQF,EAAOE,CAAG,CAAC,EAAG,CAClEH,EAAUD,EAAkBC,EAASC,EAAOE,CAAG,EAAG,CAAC,GAAGD,EAAUC,CAAG,CAAC,EACpE,QACF,CAEAH,EAAUI,EAAgBJ,EAAS,CACjC,MAAO,CAAC,GAAGE,EAAUC,CAAG,EACxB,cACA,MAAOF,EAAOE,CAAG,CACnB,CAAC,CACH,CAEA,OAAOH,CACT,CAfgBK,EAAAN,EAAA,qBCFT,SAASO,EAAYC,EAAsBC,EAAsBC,EAA+B,CACrG,MAAO,CACL,GAAGF,EACH,MAAO,KAAK,IAAI,KAAK,IAAIA,EAAQ,OAASC,EAAc,CAAC,EAAGC,CAAQ,CACtE,CACF,CALgBC,EAAAJ,EAAA,eCCT,SAASK,EACdC,EACAC,EACa,CACb,IAAIC,EAASF,EAAQ,OAEjBE,EAAO,SAAW,EACpBA,EAASD,EAAkB,IAAIE,IAAS,CAAE,MAAOA,EAAK,MAAM,GAAG,CAAE,EAAE,EAEnED,EAASF,EAAQ,OAAO,OAAOI,GAAQH,EAAkB,SAASG,EAAK,MAAM,KAAK,GAAG,CAAC,CAAC,EAGzF,IAAMC,EAAQC,EAA0BN,EAAQ,MAAOC,CAAiB,GAAK,CAAE,IAAK,CAAC,CAAE,EAEjFM,EAAQP,EAAQ,MAAM,OAAOI,GAAQH,EAAkB,SAASG,EAAK,MAAM,KAAK,GAAG,CAAC,CAAC,EAGrFI,EAAYR,EAAQ,UAAU,OAAOI,GAAQH,EAAkB,SAASG,EAAK,MAAM,KAAK,GAAG,CAAC,CAAC,EAEnG,MAAO,CACL,GAAGJ,EACH,OAAAE,EACA,MAAAG,EACA,MAAAE,EACA,UAAAC,CACF,CACF,CA1BgBC,EAAAV,EAAA,oBA4BhB,SAASO,EACPD,EACAJ,EAC8B,CAC9B,GAAII,EAAM,GACR,MAAO,CACL,GAAIA,EAAM,GACP,IAAIK,GAAKJ,EAA0BI,EAAGT,CAAiB,CAAC,EACxD,OAAOS,GAAK,CAAC,CAACA,CAAC,CACpB,EAGF,GAAIL,EAAM,IACR,MAAO,CACL,IAAKA,EAAM,IACR,IAAIK,GAAKJ,EAA0BI,EAAGT,CAAiB,CAAC,EACxD,OAAOS,GAAK,CAAC,CAACA,CAAC,CACpB,EAGF,GAAI,EAAAL,EAAM,OACJ,CAACJ,EAAkB,SAASI,EAAM,MAAM,KAAK,GAAG,CAAC,GAIvD,OAAOA,CACT,CA1BSI,EAAAH,EAAA,6BC9BF,SAASK,EACdC,EACAC,EACa,CACb,IAAMC,EAAYF,EAAQ,UAAU,OAAOG,GAAQF,EAAiB,SAASE,EAAK,MAAM,KAAK,GAAG,CAAC,CAAC,EAElG,MAAO,CACL,GAAGH,EACH,UAAAE,CACF,CACF,CAVgBE,EAAAL,EAAA","names":["filters_exports","__export","ensureCondition","ensureEqCondition","ensureLimit","filterProperties","filterRelations","__toCommonJS","ensureCondition","request","condition","__name","ensureEqCondition","request","entity","basePath","key","ensureCondition","__name","ensureLimit","request","defaultLimit","maxLimit","__name","filterProperties","request","allowedProperties","select","prop","item","where","filterPropertyAccessWhere","order","relations","__name","w","filterRelations","request","allowedRelations","relations","item","__name"]}
|
package/dist/filters/index.mjs
CHANGED
@@ -1,2 +1,2 @@
|
|
1
|
-
var m=Object.defineProperty;var t=(n,e)=>m(n,"name",{value:e,configurable:!0});function l(n,e){return n.where.and?{...n,where:{and:[
|
1
|
+
var m=Object.defineProperty;var t=(n,e)=>m(n,"name",{value:e,configurable:!0});function l(n,e){return n.where.and?{...n,where:{and:[e,...n.where.and]}}:{...n,where:{and:[e,n.where]}}}t(l,"ensureCondition");function s(n,e,i=[]){for(let o of Object.keys(e)){if(typeof e[o]=="object"&&!Array.isArray(e[o])){n=s(n,e[o],[...i,o]);continue}n=l(n,{field:[...i,o],operator:"eq",value:e[o]})}return n}t(s,"ensureEqCondition");function L(n,e,i){return{...n,limit:Math.min(Math.max(n.limit??e,1),i)}}t(L,"ensureLimit");function S(n,e){let i=n.select;i.length===0?i=e.map(r=>({field:r.split(".")})):i=n.select.filter(r=>e.includes(r.field.join(".")));let o=f(n.where,e)??{and:[]},d=n.order.filter(r=>e.includes(r.field.join("."))),u=n.relations.filter(r=>e.includes(r.field.join(".")));return{...n,select:i,where:o,order:d,relations:u}}t(S,"filterProperties");function f(n,e){if(n.or)return{or:n.or.map(i=>f(i,e)).filter(i=>!!i)};if(n.and)return{and:n.and.map(i=>f(i,e)).filter(i=>!!i)};if(!(n.field&&!e.includes(n.field.join("."))))return n}t(f,"filterPropertyAccessWhere");function v(n,e){let i=n.relations.filter(o=>e.includes(o.field.join(".")));return{...n,relations:i}}t(v,"filterRelations");export{l as ensureCondition,s as ensureEqCondition,L as ensureLimit,S as filterProperties,v as filterRelations};
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/filters/conditions/ensureCondition.ts","../../src/filters/conditions/ensureEqCondition.ts","../../src/filters/limit/ensureLimit.ts","../../src/filters/property/filterProperties.ts","../../src/filters/property/filterRelations.ts"],"sourcesContent":["import { CrudRequest } from '../../models/crud-request';\r\nimport { CrudRequestWhere } from '../../models/crud-request-where';\r\n\r\n/**\r\n * Ensures a condition is always applied to the query\r\n *\r\n * @param request The parsed request\r\n * @param condition The condition that needs to be applied\r\n */\r\nexport function ensureCondition(request: CrudRequest, condition: CrudRequestWhere): CrudRequest {\r\n // If there is already an \"AND\" condition, we'll just append to that\r\n if (request.where.and) {\r\n return {\r\n ...request,\r\n where: {\r\n and: [\r\n ...request.where.and,\r\n
|
1
|
+
{"version":3,"sources":["../../src/filters/conditions/ensureCondition.ts","../../src/filters/conditions/ensureEqCondition.ts","../../src/filters/limit/ensureLimit.ts","../../src/filters/property/filterProperties.ts","../../src/filters/property/filterRelations.ts"],"sourcesContent":["import { CrudRequest } from '../../models/crud-request';\r\nimport { CrudRequestWhere } from '../../models/crud-request-where';\r\n\r\n/**\r\n * Ensures a condition is always applied to the query\r\n *\r\n * @param request The parsed request\r\n * @param condition The condition that needs to be applied\r\n */\r\nexport function ensureCondition(request: CrudRequest, condition: CrudRequestWhere): CrudRequest {\r\n // If there is already an \"AND\" condition, we'll just append to that\r\n if (request.where.and) {\r\n return {\r\n ...request,\r\n where: {\r\n and: [\r\n condition,\r\n ...request.where.and,\r\n ]\r\n }\r\n }\r\n }\r\n\r\n return {\r\n ...request,\r\n where: {\r\n and: [\r\n condition,\r\n request.where,\r\n ],\r\n },\r\n };\r\n}\r\n","import { CrudRequest } from '../../models/crud-request';\r\nimport { ensureCondition } from './ensureCondition';\r\nimport { CrudRequestWhereOperator } from '../../models/crud-request-where';\r\n\r\n/**\r\n * Ensures a condition is always applied to the query\r\n *\r\n * @param request The parsed request\r\n * @param entity The property that need to be applied\r\n * @param basePath The field path prefix\r\n */\r\nexport function ensureEqCondition<T extends Record<string, any>>(request: CrudRequest, entity: Partial<T>, basePath: string[] = []): CrudRequest {\r\n for (const key of Object.keys(entity)) {\r\n if (typeof entity[key] === 'object' && !Array.isArray(entity[key])) {\r\n request = ensureEqCondition(request, entity[key], [...basePath, key]);\r\n continue;\r\n }\r\n\r\n request = ensureCondition(request, {\r\n field: [...basePath, key],\r\n operator: CrudRequestWhereOperator.EQ,\r\n value: entity[key],\r\n });\r\n }\r\n\r\n return request;\r\n}\r\n","import { CrudRequest } from '../../models/crud-request';\r\n\r\n/**\r\n * Ensures that the limit will be set following a maximum rule\r\n *\r\n * @param request The parsed request\r\n * @param defaultLimit The default limit number\r\n * @param maxLimit The maximum allowed limit number\r\n */\r\nexport function ensureLimit(request: CrudRequest, defaultLimit: number, maxLimit: number): CrudRequest {\r\n return {\r\n ...request,\r\n limit: Math.min(Math.max(request.limit ?? defaultLimit, 1), maxLimit),\r\n };\r\n}\r\n","import { CrudRequest } from '../../models/crud-request';\r\nimport { CrudRequestWhere } from '../../models/crud-request-where';\r\n\r\n/**\r\n * Filters access to an allowlist of properties and relations.\r\n * No selecting, filtering, sorting and joining can be done on a property that is not listed.\r\n *\r\n * @param request The parsed request\r\n * @param allowedProperties The list of properties (in case of a field path, separated by dot) that will be allowed\r\n */\r\nexport function filterProperties(\r\n request: CrudRequest,\r\n allowedProperties: string[],\r\n): CrudRequest {\r\n let select = request.select;\r\n\r\n if (select.length === 0) {\r\n select = allowedProperties.map(prop => ({ field: prop.split('.') }));\r\n } else {\r\n select = request.select.filter(item => allowedProperties.includes(item.field.join('.')));\r\n }\r\n\r\n const where = filterPropertyAccessWhere(request.where, allowedProperties) ?? { and: [] };\r\n\r\n const order = request.order.filter(item => allowedProperties.includes(item.field.join('.')));\r\n\r\n // TODO allow relations by the first part of field paths\r\n const relations = request.relations.filter(item => allowedProperties.includes(item.field.join('.')));\r\n\r\n return {\r\n ...request,\r\n select,\r\n where,\r\n order,\r\n relations,\r\n };\r\n}\r\n\r\nfunction filterPropertyAccessWhere(\r\n where: CrudRequestWhere,\r\n allowedProperties: string[],\r\n): CrudRequestWhere | undefined {\r\n if (where.or) {\r\n return {\r\n or: where.or\r\n .map(w => filterPropertyAccessWhere(w, allowedProperties))\r\n .filter(w => !!w),\r\n };\r\n }\r\n\r\n if (where.and) {\r\n return {\r\n and: where.and\r\n .map(w => filterPropertyAccessWhere(w, allowedProperties))\r\n .filter(w => !!w),\r\n };\r\n }\r\n\r\n if (where.field) {\r\n if (!allowedProperties.includes(where.field.join('.')))\r\n return undefined;\r\n }\r\n\r\n return where;\r\n}\r\n\r\n","import { CrudRequest } from '../../models/crud-request';\r\n\r\n/**\r\n * Filters access to an allowlist of relations.\r\n *\r\n * @param request The parsed request\r\n * @param allowedRelations The list of relations (in case of a field path, separated by dot) that will be allowed\r\n */\r\nexport function filterRelations(\r\n request: CrudRequest,\r\n allowedRelations: string[],\r\n): CrudRequest {\r\n const relations = request.relations.filter(item => allowedRelations.includes(item.field.join('.')));\r\n\r\n return {\r\n ...request,\r\n relations,\r\n };\r\n}\r\n"],"mappings":"+EASO,SAASA,EAAgBC,EAAsBC,EAA0C,CAE9F,OAAID,EAAQ,MAAM,IACT,CACL,GAAGA,EACH,MAAO,CACL,IAAK,CACHC,EACA,GAAGD,EAAQ,MAAM,GACnB,CACF,CACF,EAGK,CACL,GAAGA,EACH,MAAO,CACL,IAAK,CACHC,EACAD,EAAQ,KACV,CACF,CACF,CACF,CAvBgBE,EAAAH,EAAA,mBCET,SAASI,EAAiDC,EAAsBC,EAAoBC,EAAqB,CAAC,EAAgB,CAC/I,QAAWC,KAAO,OAAO,KAAKF,CAAM,EAAG,CACrC,GAAI,OAAOA,EAAOE,CAAG,GAAM,UAAY,CAAC,MAAM,QAAQF,EAAOE,CAAG,CAAC,EAAG,CAClEH,EAAUD,EAAkBC,EAASC,EAAOE,CAAG,EAAG,CAAC,GAAGD,EAAUC,CAAG,CAAC,EACpE,QACF,CAEAH,EAAUI,EAAgBJ,EAAS,CACjC,MAAO,CAAC,GAAGE,EAAUC,CAAG,EACxB,cACA,MAAOF,EAAOE,CAAG,CACnB,CAAC,CACH,CAEA,OAAOH,CACT,CAfgBK,EAAAN,EAAA,qBCFT,SAASO,EAAYC,EAAsBC,EAAsBC,EAA+B,CACrG,MAAO,CACL,GAAGF,EACH,MAAO,KAAK,IAAI,KAAK,IAAIA,EAAQ,OAASC,EAAc,CAAC,EAAGC,CAAQ,CACtE,CACF,CALgBC,EAAAJ,EAAA,eCCT,SAASK,EACdC,EACAC,EACa,CACb,IAAIC,EAASF,EAAQ,OAEjBE,EAAO,SAAW,EACpBA,EAASD,EAAkB,IAAIE,IAAS,CAAE,MAAOA,EAAK,MAAM,GAAG,CAAE,EAAE,EAEnED,EAASF,EAAQ,OAAO,OAAOI,GAAQH,EAAkB,SAASG,EAAK,MAAM,KAAK,GAAG,CAAC,CAAC,EAGzF,IAAMC,EAAQC,EAA0BN,EAAQ,MAAOC,CAAiB,GAAK,CAAE,IAAK,CAAC,CAAE,EAEjFM,EAAQP,EAAQ,MAAM,OAAOI,GAAQH,EAAkB,SAASG,EAAK,MAAM,KAAK,GAAG,CAAC,CAAC,EAGrFI,EAAYR,EAAQ,UAAU,OAAOI,GAAQH,EAAkB,SAASG,EAAK,MAAM,KAAK,GAAG,CAAC,CAAC,EAEnG,MAAO,CACL,GAAGJ,EACH,OAAAE,EACA,MAAAG,EACA,MAAAE,EACA,UAAAC,CACF,CACF,CA1BgBC,EAAAV,EAAA,oBA4BhB,SAASO,EACPD,EACAJ,EAC8B,CAC9B,GAAII,EAAM,GACR,MAAO,CACL,GAAIA,EAAM,GACP,IAAIK,GAAKJ,EAA0BI,EAAGT,CAAiB,CAAC,EACxD,OAAOS,GAAK,CAAC,CAACA,CAAC,CACpB,EAGF,GAAIL,EAAM,IACR,MAAO,CACL,IAAKA,EAAM,IACR,IAAIK,GAAKJ,EAA0BI,EAAGT,CAAiB,CAAC,EACxD,OAAOS,GAAK,CAAC,CAACA,CAAC,CACpB,EAGF,GAAI,EAAAL,EAAM,OACJ,CAACJ,EAAkB,SAASI,EAAM,MAAM,KAAK,GAAG,CAAC,GAIvD,OAAOA,CACT,CA1BSI,EAAAH,EAAA,6BC9BF,SAASK,EACdC,EACAC,EACa,CACb,IAAMC,EAAYF,EAAQ,UAAU,OAAOG,GAAQF,EAAiB,SAASE,EAAK,MAAM,KAAK,GAAG,CAAC,CAAC,EAElG,MAAO,CACL,GAAGH,EACH,UAAAE,CACF,CACF,CAVgBE,EAAAL,EAAA","names":["ensureCondition","request","condition","__name","ensureEqCondition","request","entity","basePath","key","ensureCondition","__name","ensureLimit","request","defaultLimit","maxLimit","__name","filterProperties","request","allowedProperties","select","prop","item","where","filterPropertyAccessWhere","order","relations","__name","w","filterRelations","request","allowedRelations","relations","item","__name"]}
|
@@ -0,0 +1,30 @@
|
|
1
|
+
import { RequestHandler } from 'express';
|
2
|
+
import { a as RequestParser } from '../../request-parser-DYVGG34f.mjs';
|
3
|
+
import { C as CrudRequest } from '../../crud-request-9u0s-DnI.mjs';
|
4
|
+
|
5
|
+
interface Type<T> extends Function {
|
6
|
+
new (...args: any[]): T;
|
7
|
+
}
|
8
|
+
|
9
|
+
declare global {
|
10
|
+
namespace Express {
|
11
|
+
interface Request {
|
12
|
+
/**
|
13
|
+
* Gets the CrudRequest for this request.
|
14
|
+
* This will parse the request once and memoize it.
|
15
|
+
*
|
16
|
+
* @param ignoreMemoized Whether it should parse again and ignore the memoized value.
|
17
|
+
*/
|
18
|
+
getCrudRequest: (ignoreMemoized?: boolean) => CrudRequest;
|
19
|
+
}
|
20
|
+
}
|
21
|
+
}
|
22
|
+
/**
|
23
|
+
* The crud middleware allows getting the CrudRequest through `req.getCrudRequest()`,
|
24
|
+
* which parses and memoizes the query parameters.
|
25
|
+
*
|
26
|
+
* @param instance The parser instance or class
|
27
|
+
*/
|
28
|
+
declare function crud(instance: RequestParser | Type<RequestParser>): RequestHandler;
|
29
|
+
|
30
|
+
export { crud };
|
@@ -0,0 +1,30 @@
|
|
1
|
+
import { RequestHandler } from 'express';
|
2
|
+
import { a as RequestParser } from '../../request-parser-C-cBNlki.js';
|
3
|
+
import { C as CrudRequest } from '../../crud-request-9u0s-DnI.js';
|
4
|
+
|
5
|
+
interface Type<T> extends Function {
|
6
|
+
new (...args: any[]): T;
|
7
|
+
}
|
8
|
+
|
9
|
+
declare global {
|
10
|
+
namespace Express {
|
11
|
+
interface Request {
|
12
|
+
/**
|
13
|
+
* Gets the CrudRequest for this request.
|
14
|
+
* This will parse the request once and memoize it.
|
15
|
+
*
|
16
|
+
* @param ignoreMemoized Whether it should parse again and ignore the memoized value.
|
17
|
+
*/
|
18
|
+
getCrudRequest: (ignoreMemoized?: boolean) => CrudRequest;
|
19
|
+
}
|
20
|
+
}
|
21
|
+
}
|
22
|
+
/**
|
23
|
+
* The crud middleware allows getting the CrudRequest through `req.getCrudRequest()`,
|
24
|
+
* which parses and memoizes the query parameters.
|
25
|
+
*
|
26
|
+
* @param instance The parser instance or class
|
27
|
+
*/
|
28
|
+
declare function crud(instance: RequestParser | Type<RequestParser>): RequestHandler;
|
29
|
+
|
30
|
+
export { crud };
|
@@ -0,0 +1,2 @@
|
|
1
|
+
"use strict";var u=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var o=(e,r)=>u(e,"name",{value:r,configurable:!0});var y=(e,r)=>{for(var n in r)u(e,n,{get:r[n],enumerable:!0})},c=(e,r,n,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of m(r))!b.call(e,t)&&t!==n&&u(e,t,{get:()=>r[t],enumerable:!(i=l(r,t))||i.enumerable});return e};var g=e=>c(u({},"__esModule",{value:!0}),e);var a={};y(a,{crud:()=>d});module.exports=g(a);function f(e){if(typeof e=="function")return new e;if(typeof e=="object")return e}o(f,"createInstance");function d(e){let r=f(e);if(!r)throw new Error("Invalid RequestParser instance passed");return(n,i,t)=>{let s;n.getCrudRequest=p=>((!s||p)&&(s=r.parse(n.query)),s),t()}}o(d,"crud");0&&(module.exports={crud});
|
2
|
+
//# sourceMappingURL=index.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../../../src/helpers/express/index.ts","../../../src/utils/functions.ts","../../../src/helpers/express/middlewares.ts"],"sourcesContent":["\r\nexport * from './middlewares';\r\n","export function ensurePrimitive(fieldName: string, data: any): number | string | boolean | Date {\r\n if (typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean' || data instanceof Date)\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string, number or boolean`);\r\n}\r\n\r\nexport function ensurePrimitiveOrNull(fieldName: string, data: any): number | string | boolean | Date | undefined | null {\r\n if (data === null || data === undefined)\r\n return data;\r\n\r\n if (typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean' || data instanceof Date)\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string, number, boolean or null`);\r\n}\r\n\r\nexport function ensureString(fieldName: string, data: any): string {\r\n if (typeof data === 'string')\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string`);\r\n}\r\n\r\nexport function ensureArray<T>(fieldName: string, data: T[] | any, minLength: number = 0): T[] {\r\n if (!Array.isArray(data) || data.length < minLength)\r\n throw new Error(`${fieldName} must be an array with at least ${minLength} items`);\r\n\r\n return data;\r\n}\r\n\r\nexport function ensureEmpty(fieldName: string, data: any) {\r\n if (isValid(data) && data !== true)\r\n throw new Error(`${fieldName} must be true, null or undefined`);\r\n}\r\n\r\nexport function isValid<T>(value: T | undefined | null): value is T {\r\n return value !== null && value !== undefined;\r\n}\r\n\r\nexport function getOffset(offset: number | undefined, limit?: number, page?: number): number {\r\n return offset ?? (limit && page ? limit * (page - 1) : 0);\r\n}\r\n\r\nexport interface Type<T> extends Function { new (... args: any[]): T; }\r\n\r\nexport function createInstance<T extends object>(clazzOrInstance: T | Type<T> | undefined): T | undefined {\r\n if (typeof clazzOrInstance === 'function')\r\n return new clazzOrInstance();\r\n\r\n if (typeof clazzOrInstance === 'object')\r\n return clazzOrInstance as T;\r\n\r\n return undefined;\r\n}\r\n\r\nexport function escapeRegex(str: string): string {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\n","import { Request, RequestHandler, Response } from 'express';\r\nimport { RequestParser } from '../../models/request-parser';\r\nimport { CrudRequest } from '../../models/crud-request';\r\nimport { createInstance, Type } from '../../utils/functions';\r\n\r\ndeclare global {\r\n namespace Express {\r\n interface Request {\r\n /**\r\n * Gets the CrudRequest for this request.\r\n * This will parse the request once and memoize it.\r\n *\r\n * @param ignoreMemoized Whether it should parse again and ignore the memoized value.\r\n */\r\n getCrudRequest: (ignoreMemoized?: boolean) => CrudRequest;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * The crud middleware allows getting the CrudRequest through `req.getCrudRequest()`,\r\n * which parses and memoizes the query parameters.\r\n *\r\n * @param instance The parser instance or class\r\n */\r\nexport function crud(instance: RequestParser | Type<RequestParser>): RequestHandler {\r\n const parser = createInstance(instance);\r\n\r\n if (!parser)\r\n throw new Error('Invalid RequestParser instance passed');\r\n\r\n return (req: Request, res: Response, done: (error?: Error) => void) => {\r\n let crudRequest: CrudRequest | undefined;\r\n\r\n req.getCrudRequest = (ignoreMemoized?: boolean) => {\r\n if (!crudRequest || ignoreMemoized)\r\n crudRequest = parser.parse(req.query);\r\n\r\n return crudRequest;\r\n };\r\n\r\n done();\r\n };\r\n}\r\n"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,IAAA,eAAAC,EAAAH,GC8CO,SAASI,EAAiCC,EAAyD,CACxG,GAAI,OAAOA,GAAoB,WAC7B,OAAO,IAAIA,EAEb,GAAI,OAAOA,GAAoB,SAC7B,OAAOA,CAGX,CARgBC,EAAAF,EAAA,kBCrBT,SAASG,EAAKC,EAA+D,CAClF,IAAMC,EAASC,EAAeF,CAAQ,EAEtC,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,uCAAuC,EAEzD,MAAO,CAACE,EAAcC,EAAeC,IAAkC,CACrE,IAAIC,EAEJH,EAAI,eAAkBI,KAChB,CAACD,GAAeC,KAClBD,EAAcL,EAAO,MAAME,EAAI,KAAK,GAE/BG,GAGTD,EAAK,CACP,CACF,CAlBgBG,EAAAT,EAAA","names":["express_exports","__export","crud","__toCommonJS","createInstance","clazzOrInstance","__name","crud","instance","parser","createInstance","req","res","done","crudRequest","ignoreMemoized","__name"]}
|
@@ -0,0 +1,2 @@
|
|
1
|
+
var f=Object.defineProperty;var n=(e,r)=>f(e,"name",{value:r,configurable:!0});function o(e){if(typeof e=="function")return new e;if(typeof e=="object")return e}n(o,"createInstance");function g(e){let r=o(e);if(!r)throw new Error("Invalid RequestParser instance passed");return(u,p,i)=>{let t;u.getCrudRequest=s=>((!t||s)&&(t=r.parse(u.query)),t),i()}}n(g,"crud");export{g as crud};
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/functions.ts","../../../src/helpers/express/middlewares.ts"],"sourcesContent":["export function ensurePrimitive(fieldName: string, data: any): number | string | boolean | Date {\r\n if (typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean' || data instanceof Date)\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string, number or boolean`);\r\n}\r\n\r\nexport function ensurePrimitiveOrNull(fieldName: string, data: any): number | string | boolean | Date | undefined | null {\r\n if (data === null || data === undefined)\r\n return data;\r\n\r\n if (typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean' || data instanceof Date)\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string, number, boolean or null`);\r\n}\r\n\r\nexport function ensureString(fieldName: string, data: any): string {\r\n if (typeof data === 'string')\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string`);\r\n}\r\n\r\nexport function ensureArray<T>(fieldName: string, data: T[] | any, minLength: number = 0): T[] {\r\n if (!Array.isArray(data) || data.length < minLength)\r\n throw new Error(`${fieldName} must be an array with at least ${minLength} items`);\r\n\r\n return data;\r\n}\r\n\r\nexport function ensureEmpty(fieldName: string, data: any) {\r\n if (isValid(data) && data !== true)\r\n throw new Error(`${fieldName} must be true, null or undefined`);\r\n}\r\n\r\nexport function isValid<T>(value: T | undefined | null): value is T {\r\n return value !== null && value !== undefined;\r\n}\r\n\r\nexport function getOffset(offset: number | undefined, limit?: number, page?: number): number {\r\n return offset ?? (limit && page ? limit * (page - 1) : 0);\r\n}\r\n\r\nexport interface Type<T> extends Function { new (... args: any[]): T; }\r\n\r\nexport function createInstance<T extends object>(clazzOrInstance: T | Type<T> | undefined): T | undefined {\r\n if (typeof clazzOrInstance === 'function')\r\n return new clazzOrInstance();\r\n\r\n if (typeof clazzOrInstance === 'object')\r\n return clazzOrInstance as T;\r\n\r\n return undefined;\r\n}\r\n\r\nexport function escapeRegex(str: string): string {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\n","import { Request, RequestHandler, Response } from 'express';\r\nimport { RequestParser } from '../../models/request-parser';\r\nimport { CrudRequest } from '../../models/crud-request';\r\nimport { createInstance, Type } from '../../utils/functions';\r\n\r\ndeclare global {\r\n namespace Express {\r\n interface Request {\r\n /**\r\n * Gets the CrudRequest for this request.\r\n * This will parse the request once and memoize it.\r\n *\r\n * @param ignoreMemoized Whether it should parse again and ignore the memoized value.\r\n */\r\n getCrudRequest: (ignoreMemoized?: boolean) => CrudRequest;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * The crud middleware allows getting the CrudRequest through `req.getCrudRequest()`,\r\n * which parses and memoizes the query parameters.\r\n *\r\n * @param instance The parser instance or class\r\n */\r\nexport function crud(instance: RequestParser | Type<RequestParser>): RequestHandler {\r\n const parser = createInstance(instance);\r\n\r\n if (!parser)\r\n throw new Error('Invalid RequestParser instance passed');\r\n\r\n return (req: Request, res: Response, done: (error?: Error) => void) => {\r\n let crudRequest: CrudRequest | undefined;\r\n\r\n req.getCrudRequest = (ignoreMemoized?: boolean) => {\r\n if (!crudRequest || ignoreMemoized)\r\n crudRequest = parser.parse(req.query);\r\n\r\n return crudRequest;\r\n };\r\n\r\n done();\r\n };\r\n}\r\n"],"mappings":"+EA8CO,SAASA,EAAiCC,EAAyD,CACxG,GAAI,OAAOA,GAAoB,WAC7B,OAAO,IAAIA,EAEb,GAAI,OAAOA,GAAoB,SAC7B,OAAOA,CAGX,CARgBC,EAAAF,EAAA,kBCrBT,SAASG,EAAKC,EAA+D,CAClF,IAAMC,EAASC,EAAeF,CAAQ,EAEtC,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,uCAAuC,EAEzD,MAAO,CAACE,EAAcC,EAAeC,IAAkC,CACrE,IAAIC,EAEJH,EAAI,eAAkBI,KAChB,CAACD,GAAeC,KAClBD,EAAcL,EAAO,MAAME,EAAI,KAAK,GAE/BG,GAGTD,EAAK,CACP,CACF,CAlBgBG,EAAAT,EAAA","names":["createInstance","clazzOrInstance","__name","crud","instance","parser","createInstance","req","res","done","crudRequest","ignoreMemoized","__name"]}
|
@@ -1,11 +1,12 @@
|
|
1
1
|
import * as _nestjs_common from '@nestjs/common';
|
2
2
|
import { Type } from '@nestjs/common';
|
3
|
-
import { a as RequestParser } from '../../request-parser-
|
4
|
-
import '../../crud-request-
|
3
|
+
import { a as RequestParser } from '../../request-parser-DYVGG34f.mjs';
|
4
|
+
import '../../crud-request-9u0s-DnI.mjs';
|
5
5
|
|
6
6
|
declare const CRUD_QUERY_PARSER = "crud-query-parser";
|
7
|
+
|
7
8
|
/**
|
8
|
-
* Defines which parser will be used for parsing the request
|
9
|
+
* Defines which parser will be used for parsing the request. This also adds the OpenAPI query parameters.
|
9
10
|
*
|
10
11
|
* @param parserContract The parser that will be used
|
11
12
|
*/
|
@@ -1,11 +1,12 @@
|
|
1
1
|
import * as _nestjs_common from '@nestjs/common';
|
2
2
|
import { Type } from '@nestjs/common';
|
3
|
-
import { a as RequestParser } from '../../request-parser-
|
4
|
-
import '../../crud-request-
|
3
|
+
import { a as RequestParser } from '../../request-parser-C-cBNlki.js';
|
4
|
+
import '../../crud-request-9u0s-DnI.js';
|
5
5
|
|
6
6
|
declare const CRUD_QUERY_PARSER = "crud-query-parser";
|
7
|
+
|
7
8
|
/**
|
8
|
-
* Defines which parser will be used for parsing the request
|
9
|
+
* Defines which parser will be used for parsing the request. This also adds the OpenAPI query parameters.
|
9
10
|
*
|
10
11
|
* @param parserContract The parser that will be used
|
11
12
|
*/
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var
|
1
|
+
"use strict";var p=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var o=(e,r)=>p(e,"name",{value:r,configurable:!0});var g=(e,r)=>{for(var t in r)p(e,t,{get:r[t],enumerable:!0})},q=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let u of y(r))!l.call(e,u)&&u!==t&&p(e,u,{get:()=>r[u],enumerable:!(n=R(r,u))||n.enumerable});return e};var x=e=>q(p({},"__esModule",{value:!0}),e);var C={};g(C,{CRUD_QUERY_PARSER:()=>i,Crud:()=>T,ParseCrudRequest:()=>P});module.exports=x(C);var s=require("@nestjs/common");function a(e){if(typeof e=="function")return new e;if(typeof e=="object")return e}o(a,"createInstance");var c=require("@nestjs/common");function f(e){return{select:[],relations:[],order:[],where:{and:[]},...e}}o(f,"createCrudRequest");var i="crud-query-parser",m=(()=>{try{return require("@nestjs/swagger").ApiQuery}catch{return r=>()=>{}}})();function b(e,r){let t=[e.getHandler(),e.getClass()];for(let n of t){let u=Reflect.getMetadata(r,n);if(u)return u}}o(b,"getMetadataFromContext");function d(e,r){let t=r.switchToHttp().getRequest(),n=e?a(e):b(r,i);return n?n.parse(t.query):(new c.Logger("ParseCrudRequest").warn("No crud request parser found. Please, define one with @Crud() or pass to @ParseCrudRequest()"),f())}o(d,"parseCrudRequest");function T(e){let r=a(e);if(!r)throw new Error("The request parser passed to @Crud() is invalid");let t=r.getOpenAPIParameters().map(n=>m(n));return(0,s.applyDecorators)((0,s.SetMetadata)(i,r),...t)}o(T,"Crud");var P=(0,s.createParamDecorator)(d);0&&(module.exports={CRUD_QUERY_PARSER,Crud,ParseCrudRequest});
|
2
2
|
//# sourceMappingURL=index.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/helpers/nestjs/index.ts","../../../src/helpers/nestjs/decorators.ts","../../../src/helpers/nestjs/utils.ts"],"sourcesContent":["\r\nexport * from './decorators';\r\n","import { applyDecorators, createParamDecorator,
|
1
|
+
{"version":3,"sources":["../../../src/helpers/nestjs/index.ts","../../../src/helpers/nestjs/decorators.ts","../../../src/utils/functions.ts","../../../src/helpers/nestjs/utils.ts","../../../src/utils/objects.ts"],"sourcesContent":["\r\nexport * from './decorators';\r\n","import { applyDecorators, createParamDecorator, SetMetadata, Type } from '@nestjs/common';\r\nimport { RequestParser } from '../../models/request-parser';\r\nimport { createInstance } from '../../utils/functions';\r\nimport { ApiQuery, CRUD_QUERY_PARSER, parseCrudRequest } from './utils';\r\n\r\nexport { CRUD_QUERY_PARSER } from './utils';\r\n\r\n/**\r\n * Defines which parser will be used for parsing the request. This also adds the OpenAPI query parameters.\r\n *\r\n * @param parserContract The parser that will be used\r\n */\r\nexport function Crud(parserContract: RequestParser | Type<RequestParser>): MethodDecorator & ClassDecorator {\r\n const parser = createInstance(parserContract);\r\n\r\n if (!parser) {\r\n throw new Error('The request parser passed to @Crud() is invalid');\r\n }\r\n\r\n const openApi = parser.getOpenAPIParameters().map(param => ApiQuery(param));\r\n\r\n return applyDecorators(\r\n SetMetadata(CRUD_QUERY_PARSER, parser),\r\n ...openApi,\r\n );\r\n}\r\n\r\n/**\r\n * A parameter decorator that converts the query string into a `CrudRequest` object\r\n */\r\nexport const ParseCrudRequest = createParamDecorator<RequestParser | Type<RequestParser>>(parseCrudRequest);\r\n","export function ensurePrimitive(fieldName: string, data: any): number | string | boolean | Date {\r\n if (typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean' || data instanceof Date)\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string, number or boolean`);\r\n}\r\n\r\nexport function ensurePrimitiveOrNull(fieldName: string, data: any): number | string | boolean | Date | undefined | null {\r\n if (data === null || data === undefined)\r\n return data;\r\n\r\n if (typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean' || data instanceof Date)\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string, number, boolean or null`);\r\n}\r\n\r\nexport function ensureString(fieldName: string, data: any): string {\r\n if (typeof data === 'string')\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string`);\r\n}\r\n\r\nexport function ensureArray<T>(fieldName: string, data: T[] | any, minLength: number = 0): T[] {\r\n if (!Array.isArray(data) || data.length < minLength)\r\n throw new Error(`${fieldName} must be an array with at least ${minLength} items`);\r\n\r\n return data;\r\n}\r\n\r\nexport function ensureEmpty(fieldName: string, data: any) {\r\n if (isValid(data) && data !== true)\r\n throw new Error(`${fieldName} must be true, null or undefined`);\r\n}\r\n\r\nexport function isValid<T>(value: T | undefined | null): value is T {\r\n return value !== null && value !== undefined;\r\n}\r\n\r\nexport function getOffset(offset: number | undefined, limit?: number, page?: number): number {\r\n return offset ?? (limit && page ? limit * (page - 1) : 0);\r\n}\r\n\r\nexport interface Type<T> extends Function { new (... args: any[]): T; }\r\n\r\nexport function createInstance<T extends object>(clazzOrInstance: T | Type<T> | undefined): T | undefined {\r\n if (typeof clazzOrInstance === 'function')\r\n return new clazzOrInstance();\r\n\r\n if (typeof clazzOrInstance === 'object')\r\n return clazzOrInstance as T;\r\n\r\n return undefined;\r\n}\r\n\r\nexport function escapeRegex(str: string): string {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\n","import { ExecutionContext, Logger, Type } from '@nestjs/common';\r\nimport { OpenAPIParameter } from '../../models/openapi-parameter';\r\nimport { RequestParser } from '../../models/request-parser';\r\nimport { CrudRequest } from '../../models/crud-request';\r\nimport { createInstance } from '../../utils/functions';\r\nimport { createCrudRequest } from '../../utils/objects';\r\n\r\nexport const CRUD_QUERY_PARSER = 'crud-query-parser';\r\n\r\nexport const ApiQuery = (() => {\r\n try {\r\n return require('@nestjs/swagger').ApiQuery; // TODO ES6 imports?\r\n } catch (error) {\r\n return (options: OpenAPIParameter): MethodDecorator => {\r\n return () => {};\r\n };\r\n }\r\n})();\r\n\r\nexport function getMetadataFromContext<T>(context: ExecutionContext, key: string): T | undefined {\r\n const targets = [\r\n context.getHandler(),\r\n context.getClass(),\r\n ];\r\n\r\n for (const target of targets) {\r\n const data = Reflect.getMetadata(key, target);\r\n\r\n if (data)\r\n return data;\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\nexport function parseCrudRequest(data: RequestParser | Type<RequestParser> | undefined, ctx: ExecutionContext): CrudRequest {\r\n const request = ctx.switchToHttp().getRequest();\r\n const parser = data ? createInstance(data) : getMetadataFromContext<RequestParser>(ctx, CRUD_QUERY_PARSER);\r\n\r\n if (!parser) {\r\n new Logger('ParseCrudRequest').warn(`No crud request parser found. Please, define one with @Crud() or pass to @ParseCrudRequest()`);\r\n\r\n return createCrudRequest();\r\n }\r\n\r\n return parser.parse(request.query);\r\n}\r\n","import { GetManyResult } from '../models/get-many-result';\r\nimport { CrudRequest } from '../models/crud-request';\r\n\r\n/**\r\n * Creates a CrudRequest object, filling required missing properties with empty values\r\n */\r\nexport function createCrudRequest(crudRequest?: Partial<CrudRequest>): CrudRequest {\r\n return {\r\n select: [],\r\n relations: [],\r\n order: [],\r\n where: { and: [] },\r\n ...crudRequest,\r\n };\r\n}\r\n\r\n/**\r\n * Creates a GetManyResult object\r\n *\r\n * @param data The entity list to be returned\r\n * @param total The total amount of entities in the database\r\n * @param offset The offset used for querying\r\n * @param limit The limit used for querying\r\n */\r\nexport function createGetManyResult<T>(data: T[], total: number, offset: number, limit?: number): GetManyResult<T> {\r\n const count = data.length;\r\n const actualLimit = limit ?? total;\r\n const page = actualLimit > 0 ? Math.floor(offset / actualLimit) + 1 : 1;\r\n const pageCount = actualLimit > 0 ? Math.ceil(total / actualLimit) : 0;\r\n\r\n return {\r\n data,\r\n count,\r\n total,\r\n page,\r\n pageCount,\r\n };\r\n}\r\n"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,uBAAAE,EAAA,SAAAC,EAAA,qBAAAC,IAAA,eAAAC,EAAAL,GCAA,IAAAM,EAAyE,0BC8ClE,SAASC,EAAiCC,EAAyD,CACxG,GAAI,OAAOA,GAAoB,WAC7B,OAAO,IAAIA,EAEb,GAAI,OAAOA,GAAoB,SAC7B,OAAOA,CAGX,CARgBC,EAAAF,EAAA,kBC9ChB,IAAAG,EAA+C,0BCMxC,SAASC,EAAkBC,EAAiD,CACjF,MAAO,CACL,OAAQ,CAAC,EACT,UAAW,CAAC,EACZ,MAAO,CAAC,EACR,MAAO,CAAE,IAAK,CAAC,CAAE,EACjB,GAAGA,CACL,CACF,CARgBC,EAAAF,EAAA,qBDCT,IAAMG,EAAoB,oBAEpBC,GAAY,IAAM,CAC7B,GAAI,CACF,MAAO,SAAQ,iBAAiB,EAAE,QACpC,MAAgB,CACd,OAAQC,GACC,IAAM,CAAC,CAElB,CACF,GAAG,EAEI,SAASC,EAA0BC,EAA2BC,EAA4B,CAC/F,IAAMC,EAAU,CACdF,EAAQ,WAAW,EACnBA,EAAQ,SAAS,CACnB,EAEA,QAAWG,KAAUD,EAAS,CAC5B,IAAME,EAAO,QAAQ,YAAYH,EAAKE,CAAM,EAE5C,GAAIC,EACF,OAAOA,CACX,CAGF,CAdgBC,EAAAN,EAAA,0BAgBT,SAASO,EAAiBF,EAAuDG,EAAoC,CAC1H,IAAMC,EAAUD,EAAI,aAAa,EAAE,WAAW,EACxCE,EAASL,EAAOM,EAAeN,CAAI,EAAIL,EAAsCQ,EAAKX,CAAiB,EAEzG,OAAKa,EAMEA,EAAO,MAAMD,EAAQ,KAAK,GAL/B,IAAI,SAAO,kBAAkB,EAAE,KAAK,8FAA8F,EAE3HG,EAAkB,EAI7B,CAXgBN,EAAAC,EAAA,oBFvBT,SAASM,EAAKC,EAAuF,CAC1G,IAAMC,EAASC,EAAeF,CAAc,EAE5C,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,iDAAiD,EAGnE,IAAME,EAAUF,EAAO,qBAAqB,EAAE,IAAIG,GAASC,EAASD,CAAK,CAAC,EAE1E,SAAO,sBACL,eAAYE,EAAmBL,CAAM,EACrC,GAAGE,CACL,CACF,CAbgBI,EAAAR,EAAA,QAkBT,IAAMS,KAAmB,wBAA0DC,CAAgB","names":["nestjs_exports","__export","CRUD_QUERY_PARSER","Crud","ParseCrudRequest","__toCommonJS","import_common","createInstance","clazzOrInstance","__name","import_common","createCrudRequest","crudRequest","__name","CRUD_QUERY_PARSER","ApiQuery","options","getMetadataFromContext","context","key","targets","target","data","__name","parseCrudRequest","ctx","request","parser","createInstance","createCrudRequest","Crud","parserContract","parser","createInstance","openApi","param","ApiQuery","CRUD_QUERY_PARSER","__name","ParseCrudRequest","parseCrudRequest"]}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
var c=Object.defineProperty;var
|
1
|
+
var c=Object.defineProperty;var t=(e,r)=>c(e,"name",{value:r,configurable:!0}),m=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,n)=>(typeof require<"u"?require:r)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{applyDecorators as y,createParamDecorator as l,SetMetadata as g}from"@nestjs/common";function u(e){if(typeof e=="function")return new e;if(typeof e=="object")return e}t(u,"createInstance");import{Logger as d}from"@nestjs/common";function p(e){return{select:[],relations:[],order:[],where:{and:[]},...e}}t(p,"createCrudRequest");var s="crud-query-parser",a=(()=>{try{return m("@nestjs/swagger").ApiQuery}catch{return r=>()=>{}}})();function R(e,r){let n=[e.getHandler(),e.getClass()];for(let o of n){let i=Reflect.getMetadata(r,o);if(i)return i}}t(R,"getMetadataFromContext");function f(e,r){let n=r.switchToHttp().getRequest(),o=e?u(e):R(r,s);return o?o.parse(n.query):(new d("ParseCrudRequest").warn("No crud request parser found. Please, define one with @Crud() or pass to @ParseCrudRequest()"),p())}t(f,"parseCrudRequest");function S(e){let r=u(e);if(!r)throw new Error("The request parser passed to @Crud() is invalid");let n=r.getOpenAPIParameters().map(o=>a(o));return y(g(s,r),...n)}t(S,"Crud");var v=l(f);export{s as CRUD_QUERY_PARSER,S as Crud,v as ParseCrudRequest};
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/helpers/nestjs/decorators.ts","../../../src/helpers/nestjs/utils.ts"],"sourcesContent":["import { applyDecorators, createParamDecorator,
|
1
|
+
{"version":3,"sources":["../../../src/helpers/nestjs/decorators.ts","../../../src/utils/functions.ts","../../../src/helpers/nestjs/utils.ts","../../../src/utils/objects.ts"],"sourcesContent":["import { applyDecorators, createParamDecorator, SetMetadata, Type } from '@nestjs/common';\r\nimport { RequestParser } from '../../models/request-parser';\r\nimport { createInstance } from '../../utils/functions';\r\nimport { ApiQuery, CRUD_QUERY_PARSER, parseCrudRequest } from './utils';\r\n\r\nexport { CRUD_QUERY_PARSER } from './utils';\r\n\r\n/**\r\n * Defines which parser will be used for parsing the request. This also adds the OpenAPI query parameters.\r\n *\r\n * @param parserContract The parser that will be used\r\n */\r\nexport function Crud(parserContract: RequestParser | Type<RequestParser>): MethodDecorator & ClassDecorator {\r\n const parser = createInstance(parserContract);\r\n\r\n if (!parser) {\r\n throw new Error('The request parser passed to @Crud() is invalid');\r\n }\r\n\r\n const openApi = parser.getOpenAPIParameters().map(param => ApiQuery(param));\r\n\r\n return applyDecorators(\r\n SetMetadata(CRUD_QUERY_PARSER, parser),\r\n ...openApi,\r\n );\r\n}\r\n\r\n/**\r\n * A parameter decorator that converts the query string into a `CrudRequest` object\r\n */\r\nexport const ParseCrudRequest = createParamDecorator<RequestParser | Type<RequestParser>>(parseCrudRequest);\r\n","export function ensurePrimitive(fieldName: string, data: any): number | string | boolean | Date {\r\n if (typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean' || data instanceof Date)\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string, number or boolean`);\r\n}\r\n\r\nexport function ensurePrimitiveOrNull(fieldName: string, data: any): number | string | boolean | Date | undefined | null {\r\n if (data === null || data === undefined)\r\n return data;\r\n\r\n if (typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean' || data instanceof Date)\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string, number, boolean or null`);\r\n}\r\n\r\nexport function ensureString(fieldName: string, data: any): string {\r\n if (typeof data === 'string')\r\n return data;\r\n\r\n throw new Error(`${fieldName} must be a string`);\r\n}\r\n\r\nexport function ensureArray<T>(fieldName: string, data: T[] | any, minLength: number = 0): T[] {\r\n if (!Array.isArray(data) || data.length < minLength)\r\n throw new Error(`${fieldName} must be an array with at least ${minLength} items`);\r\n\r\n return data;\r\n}\r\n\r\nexport function ensureEmpty(fieldName: string, data: any) {\r\n if (isValid(data) && data !== true)\r\n throw new Error(`${fieldName} must be true, null or undefined`);\r\n}\r\n\r\nexport function isValid<T>(value: T | undefined | null): value is T {\r\n return value !== null && value !== undefined;\r\n}\r\n\r\nexport function getOffset(offset: number | undefined, limit?: number, page?: number): number {\r\n return offset ?? (limit && page ? limit * (page - 1) : 0);\r\n}\r\n\r\nexport interface Type<T> extends Function { new (... args: any[]): T; }\r\n\r\nexport function createInstance<T extends object>(clazzOrInstance: T | Type<T> | undefined): T | undefined {\r\n if (typeof clazzOrInstance === 'function')\r\n return new clazzOrInstance();\r\n\r\n if (typeof clazzOrInstance === 'object')\r\n return clazzOrInstance as T;\r\n\r\n return undefined;\r\n}\r\n\r\nexport function escapeRegex(str: string): string {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\n","import { ExecutionContext, Logger, Type } from '@nestjs/common';\r\nimport { OpenAPIParameter } from '../../models/openapi-parameter';\r\nimport { RequestParser } from '../../models/request-parser';\r\nimport { CrudRequest } from '../../models/crud-request';\r\nimport { createInstance } from '../../utils/functions';\r\nimport { createCrudRequest } from '../../utils/objects';\r\n\r\nexport const CRUD_QUERY_PARSER = 'crud-query-parser';\r\n\r\nexport const ApiQuery = (() => {\r\n try {\r\n return require('@nestjs/swagger').ApiQuery; // TODO ES6 imports?\r\n } catch (error) {\r\n return (options: OpenAPIParameter): MethodDecorator => {\r\n return () => {};\r\n };\r\n }\r\n})();\r\n\r\nexport function getMetadataFromContext<T>(context: ExecutionContext, key: string): T | undefined {\r\n const targets = [\r\n context.getHandler(),\r\n context.getClass(),\r\n ];\r\n\r\n for (const target of targets) {\r\n const data = Reflect.getMetadata(key, target);\r\n\r\n if (data)\r\n return data;\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\nexport function parseCrudRequest(data: RequestParser | Type<RequestParser> | undefined, ctx: ExecutionContext): CrudRequest {\r\n const request = ctx.switchToHttp().getRequest();\r\n const parser = data ? createInstance(data) : getMetadataFromContext<RequestParser>(ctx, CRUD_QUERY_PARSER);\r\n\r\n if (!parser) {\r\n new Logger('ParseCrudRequest').warn(`No crud request parser found. Please, define one with @Crud() or pass to @ParseCrudRequest()`);\r\n\r\n return createCrudRequest();\r\n }\r\n\r\n return parser.parse(request.query);\r\n}\r\n","import { GetManyResult } from '../models/get-many-result';\r\nimport { CrudRequest } from '../models/crud-request';\r\n\r\n/**\r\n * Creates a CrudRequest object, filling required missing properties with empty values\r\n */\r\nexport function createCrudRequest(crudRequest?: Partial<CrudRequest>): CrudRequest {\r\n return {\r\n select: [],\r\n relations: [],\r\n order: [],\r\n where: { and: [] },\r\n ...crudRequest,\r\n };\r\n}\r\n\r\n/**\r\n * Creates a GetManyResult object\r\n *\r\n * @param data The entity list to be returned\r\n * @param total The total amount of entities in the database\r\n * @param offset The offset used for querying\r\n * @param limit The limit used for querying\r\n */\r\nexport function createGetManyResult<T>(data: T[], total: number, offset: number, limit?: number): GetManyResult<T> {\r\n const count = data.length;\r\n const actualLimit = limit ?? total;\r\n const page = actualLimit > 0 ? Math.floor(offset / actualLimit) + 1 : 1;\r\n const pageCount = actualLimit > 0 ? Math.ceil(total / actualLimit) : 0;\r\n\r\n return {\r\n data,\r\n count,\r\n total,\r\n page,\r\n pageCount,\r\n };\r\n}\r\n"],"mappings":"oUAAA,OAAS,mBAAAA,EAAiB,wBAAAC,EAAsB,eAAAC,MAAyB,iBC8ClE,SAASC,EAAiCC,EAAyD,CACxG,GAAI,OAAOA,GAAoB,WAC7B,OAAO,IAAIA,EAEb,GAAI,OAAOA,GAAoB,SAC7B,OAAOA,CAGX,CARgBC,EAAAF,EAAA,kBC9ChB,OAA2B,UAAAG,MAAoB,iBCMxC,SAASC,EAAkBC,EAAiD,CACjF,MAAO,CACL,OAAQ,CAAC,EACT,UAAW,CAAC,EACZ,MAAO,CAAC,EACR,MAAO,CAAE,IAAK,CAAC,CAAE,EACjB,GAAGA,CACL,CACF,CARgBC,EAAAF,EAAA,qBDCT,IAAMG,EAAoB,oBAEpBC,GAAY,IAAM,CAC7B,GAAI,CACF,MAAO,GAAQ,iBAAiB,EAAE,QACpC,MAAgB,CACd,OAAQC,GACC,IAAM,CAAC,CAElB,CACF,GAAG,EAEI,SAASC,EAA0BC,EAA2BC,EAA4B,CAC/F,IAAMC,EAAU,CACdF,EAAQ,WAAW,EACnBA,EAAQ,SAAS,CACnB,EAEA,QAAWG,KAAUD,EAAS,CAC5B,IAAME,EAAO,QAAQ,YAAYH,EAAKE,CAAM,EAE5C,GAAIC,EACF,OAAOA,CACX,CAGF,CAdgBC,EAAAN,EAAA,0BAgBT,SAASO,EAAiBF,EAAuDG,EAAoC,CAC1H,IAAMC,EAAUD,EAAI,aAAa,EAAE,WAAW,EACxCE,EAASL,EAAOM,EAAeN,CAAI,EAAIL,EAAsCQ,EAAKX,CAAiB,EAEzG,OAAKa,EAMEA,EAAO,MAAMD,EAAQ,KAAK,GAL/B,IAAIG,EAAO,kBAAkB,EAAE,KAAK,8FAA8F,EAE3HC,EAAkB,EAI7B,CAXgBP,EAAAC,EAAA,oBFvBT,SAASO,EAAKC,EAAuF,CAC1G,IAAMC,EAASC,EAAeF,CAAc,EAE5C,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,iDAAiD,EAGnE,IAAME,EAAUF,EAAO,qBAAqB,EAAE,IAAIG,GAASC,EAASD,CAAK,CAAC,EAE1E,OAAOE,EACLC,EAAYC,EAAmBP,CAAM,EACrC,GAAGE,CACL,CACF,CAbgBM,EAAAV,EAAA,QAkBT,IAAMW,EAAmBC,EAA0DC,CAAgB","names":["applyDecorators","createParamDecorator","SetMetadata","createInstance","clazzOrInstance","__name","Logger","createCrudRequest","crudRequest","__name","CRUD_QUERY_PARSER","ApiQuery","options","getMetadataFromContext","context","key","targets","target","data","__name","parseCrudRequest","ctx","request","parser","createInstance","Logger","createCrudRequest","Crud","parserContract","parser","createInstance","openApi","param","ApiQuery","applyDecorators","SetMetadata","CRUD_QUERY_PARSER","__name","ParseCrudRequest","createParamDecorator","parseCrudRequest"]}
|
package/dist/index.d.mts
CHANGED
@@ -1,4 +1,12 @@
|
|
1
|
-
export { G as GetManyResult, Q as QueryAdapter } from './query-adapter-
|
2
|
-
export { R as RequestParamValue, a as RequestParser } from './request-parser-
|
3
|
-
|
4
|
-
export {
|
1
|
+
export { G as GetManyResult, Q as QueryAdapter } from './query-adapter-HqVhBKtl.mjs';
|
2
|
+
export { R as RequestParamValue, a as RequestParser } from './request-parser-DYVGG34f.mjs';
|
3
|
+
import { C as CrudRequest } from './crud-request-9u0s-DnI.mjs';
|
4
|
+
export { a as CrudRequestFields, c as CrudRequestOrder, b as CrudRequestRelation, d as CrudRequestWhere, e as CrudRequestWhereAND, g as CrudRequestWhereField, f as CrudRequestWhereOR, i as CrudRequestWhereOperator, h as CrudRequestWhereValueType, F as FieldPath, P as ParsedRequestSelect } from './crud-request-9u0s-DnI.mjs';
|
5
|
+
export { C as CrudRequestWhereBuilder } from './crud-request-where.builder-D_V4JtjY.mjs';
|
6
|
+
|
7
|
+
/**
|
8
|
+
* Creates a CrudRequest object, filling required missing properties with empty values
|
9
|
+
*/
|
10
|
+
declare function createCrudRequest(crudRequest?: Partial<CrudRequest>): CrudRequest;
|
11
|
+
|
12
|
+
export { CrudRequest, createCrudRequest };
|