prisma-generator-express 1.12.0 → 1.14.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.
Files changed (67) hide show
  1. package/README.md +87 -17
  2. package/dist/generator.js +2 -12
  3. package/dist/generator.js.map +1 -1
  4. package/dist/helpers/generateAggregate.js +13 -13
  5. package/dist/helpers/generateAggregate.js.map +1 -1
  6. package/dist/helpers/generateCount.js +12 -13
  7. package/dist/helpers/generateCount.js.map +1 -1
  8. package/dist/helpers/generateCreate.js +13 -15
  9. package/dist/helpers/generateCreate.js.map +1 -1
  10. package/dist/helpers/generateCreateMany.js +13 -15
  11. package/dist/helpers/generateCreateMany.js.map +1 -1
  12. package/dist/helpers/generateDelete.js +12 -15
  13. package/dist/helpers/generateDelete.js.map +1 -1
  14. package/dist/helpers/generateDeleteMany.js +13 -14
  15. package/dist/helpers/generateDeleteMany.js.map +1 -1
  16. package/dist/helpers/generateFindFirst.js +10 -15
  17. package/dist/helpers/generateFindFirst.js.map +1 -1
  18. package/dist/helpers/generateFindMany.js +10 -15
  19. package/dist/helpers/generateFindMany.js.map +1 -1
  20. package/dist/helpers/generateFindUnique.js +10 -15
  21. package/dist/helpers/generateFindUnique.js.map +1 -1
  22. package/dist/helpers/generateGroupBy.js +12 -13
  23. package/dist/helpers/generateGroupBy.js.map +1 -1
  24. package/dist/helpers/generateRouteFile.js +68 -35
  25. package/dist/helpers/generateRouteFile.js.map +1 -1
  26. package/dist/helpers/generateUpdate.js +12 -15
  27. package/dist/helpers/generateUpdate.js.map +1 -1
  28. package/dist/helpers/generateUpdateMany.js +12 -15
  29. package/dist/helpers/generateUpdateMany.js.map +1 -1
  30. package/dist/helpers/generateUpsert.js +12 -15
  31. package/dist/helpers/generateUpsert.js.map +1 -1
  32. package/dist/utils/copyFiles.js +26 -0
  33. package/dist/utils/copyFiles.js.map +1 -0
  34. package/package.json +4 -1
  35. package/src/copy/createOutputValidatorMiddleware.ts +44 -0
  36. package/src/copy/createValidatorMiddleware.ts +55 -0
  37. package/src/copy/encodeQueryParams.spec.ts +303 -0
  38. package/src/copy/encodeQueryParams.ts +44 -0
  39. package/src/copy/misc.spec.ts +62 -0
  40. package/src/copy/misc.ts +25 -0
  41. package/src/copy/parseQueryParams.spec.ts +187 -0
  42. package/src/copy/parseQueryParams.ts +42 -0
  43. package/src/copy/routeConfig.ts +34 -0
  44. package/src/copy/transformZod.spec.ts +714 -0
  45. package/src/copy/transformZod.ts +140 -0
  46. package/src/generator.ts +3 -13
  47. package/src/helpers/generateAggregate.ts +13 -13
  48. package/src/helpers/generateCount.ts +12 -13
  49. package/src/helpers/generateCreate.ts +14 -15
  50. package/src/helpers/generateCreateMany.ts +13 -15
  51. package/src/helpers/generateDelete.ts +13 -15
  52. package/src/helpers/generateDeleteMany.ts +14 -14
  53. package/src/helpers/generateFindFirst.ts +10 -15
  54. package/src/helpers/generateFindMany.ts +10 -15
  55. package/src/helpers/generateFindUnique.ts +10 -15
  56. package/src/helpers/generateGroupBy.ts +12 -13
  57. package/src/helpers/generateRouteFile.ts +68 -35
  58. package/src/helpers/generateUpdate.ts +13 -15
  59. package/src/helpers/generateUpdateMany.ts +13 -15
  60. package/src/helpers/generateUpsert.ts +13 -15
  61. package/src/utils/copyFiles.ts +27 -0
  62. package/dist/helpers/generateQsParser.js +0 -56
  63. package/dist/helpers/generateQsParser.js.map +0 -1
  64. package/dist/helpers/generateRouteConfigType.js +0 -34
  65. package/dist/helpers/generateRouteConfigType.js.map +0 -1
  66. package/src/helpers/generateQsParser.ts +0 -51
  67. package/src/helpers/generateRouteConfigType.ts +0 -29
@@ -0,0 +1,44 @@
1
+ import { NextFunction } from 'express'
2
+ import { allow, forbid } from './transformZod'
3
+ import { ValidatorOptions } from './createValidatorMiddleware'
4
+
5
+ /**
6
+ * Creates a middleware for validating response data using a Zod schema.
7
+ * @param {ValidatorOptions} options - The validation options.
8
+ * @param {ZodSchema<any>} options.schema - The Zod schema to validate the response data.
9
+ * @param {string[]} [options.allowedPaths] - Paths that are allowed in the response data.
10
+ * @param {string[]} [options.forbiddenPaths] - Paths that are forbidden in the response data.
11
+ * @returns {function} Express middleware function.
12
+ */
13
+ export function createOutputValidatorMiddleware({
14
+ schema,
15
+ allowedPaths,
16
+ forbiddenPaths,
17
+ }: ValidatorOptions) {
18
+ if (allowedPaths) {
19
+ schema = allow(schema, allowedPaths)
20
+ }
21
+
22
+ if (forbiddenPaths) {
23
+ schema = forbid(schema, forbiddenPaths)
24
+ }
25
+
26
+ return (req: Request, res: Response, next: NextFunction) => {
27
+ const originalSend = res.send
28
+
29
+ res.send = function (data) {
30
+ const validationResult = schema.safeParse(data)
31
+ if (!validationResult.success) {
32
+ const errors = validationResult.error.errors
33
+ return next({
34
+ status: 400,
35
+ message: 'Output validation failed',
36
+ errors,
37
+ })
38
+ }
39
+ return originalSend.call(this, data)
40
+ }
41
+
42
+ next()
43
+ }
44
+ }
@@ -0,0 +1,55 @@
1
+ import { Request, Response, NextFunction } from 'express'
2
+ import { ZodSchema } from 'zod'
3
+ import { allow, forbid } from './transformZod'
4
+
5
+ export interface ValidatorOptions {
6
+ schema: ZodSchema<any>
7
+ allowedPaths?: string[]
8
+ forbiddenPaths?: string[]
9
+ target?: 'body' | 'query'
10
+ }
11
+
12
+ /**
13
+ * Creates a middleware for validating request data using a Zod schema.
14
+ * @param {ValidatorOptions} options - The validation options.
15
+ * @param {ZodSchema<any>} options.schema - The Zod schema to validate the request data.
16
+ * @param {string[]} [options.allowedPaths] - Paths that are allowed in the request data. For example [`where.user.id`, `select.id`]
17
+ * @param {string[]} [options.forbiddenPaths] - Paths that are forbidden in the request data.
18
+ * @param {'body' | 'query'} [options.target='body'] - The part of the request to validate ('body' or 'query').
19
+ * @returns {function} Express middleware function.
20
+ */
21
+ export function createValidatorMiddleware({
22
+ schema,
23
+ allowedPaths,
24
+ forbiddenPaths,
25
+ target = 'body',
26
+ }: ValidatorOptions) {
27
+ if (allowedPaths) {
28
+ schema = allow(schema, allowedPaths)
29
+ }
30
+
31
+ if (forbiddenPaths) {
32
+ schema = forbid(schema, forbiddenPaths)
33
+ }
34
+
35
+ return (req: Request, res: Response, next: NextFunction) => {
36
+ let validationResult
37
+
38
+ if (target === 'query') {
39
+ validationResult = schema.safeParse(req.query)
40
+ } else {
41
+ validationResult = schema.safeParse(req.body)
42
+ }
43
+
44
+ if (!validationResult.success) {
45
+ const errors = validationResult.error.errors
46
+ return next({
47
+ status: 400,
48
+ message: 'Validation failed',
49
+ errors,
50
+ })
51
+ }
52
+
53
+ next()
54
+ }
55
+ }
@@ -0,0 +1,303 @@
1
+ import { encodeQueryParams } from './encodeQueryParams'
2
+
3
+ describe('Query Params Encoding', () => {
4
+ it('should encode simple key-value pairs correctly', () => {
5
+ const params = {
6
+ id: 1,
7
+ name: 'test',
8
+ }
9
+ const result = encodeQueryParams(params)
10
+ expect(result).toBe('id=1&name=test')
11
+ })
12
+
13
+ it('should encode nested objects correctly', () => {
14
+ const params = {
15
+ select: {
16
+ id: true,
17
+ name: true,
18
+ },
19
+ }
20
+ const result = encodeQueryParams(params)
21
+ expect(result).toBe('select%5Bid%5D=true&select%5Bname%5D=true')
22
+ })
23
+
24
+ it('should encode arrays correctly', () => {
25
+ const params = {
26
+ ids: [1, 2, 3],
27
+ }
28
+ const result = encodeQueryParams(params)
29
+ expect(result).toBe('ids%5B0%5D=1&ids%5B1%5D=2&ids%5B2%5D=3')
30
+ })
31
+
32
+ it('should encode complex nested objects correctly', () => {
33
+ const params = {
34
+ select: {
35
+ id: true,
36
+ project_id: true,
37
+ list_id: true,
38
+ user_assignments: {
39
+ select: {
40
+ user: true,
41
+ },
42
+ },
43
+ tags_mappings: {
44
+ select: {
45
+ tag: true,
46
+ },
47
+ },
48
+ attachments: {
49
+ select: {
50
+ attachment: true,
51
+ },
52
+ where: {
53
+ is_image: true,
54
+ },
55
+ take: 100,
56
+ orderBy: {
57
+ created_at: 'desc',
58
+ },
59
+ },
60
+ rendered_description: true,
61
+ description: true,
62
+ created_at: true,
63
+ start_date: true,
64
+ reactions: true,
65
+ intervals: true,
66
+ column_id: true,
67
+ priority: true,
68
+ due_date: true,
69
+ column: true,
70
+ title: true,
71
+ order: true,
72
+ color: true,
73
+ },
74
+ where: {
75
+ id: 'task_id',
76
+ AND: [
77
+ {
78
+ OR: [{ to_delete: false }, { to_delete: null }],
79
+ },
80
+ ],
81
+ },
82
+ }
83
+ const result = encodeQueryParams(params)
84
+ expect(result).toBe(
85
+ 'select%5Bid%5D=true&select%5Bproject_id%5D=true&select%5Blist_id%5D=true&select%5Buser_assignments%5D%5Bselect%5D%5Buser%5D=true&select%5Btags_mappings%5D%5Bselect%5D%5Btag%5D=true&select%5Battachments%5D%5Bselect%5D%5Battachment%5D=true&select%5Battachments%5D%5Bwhere%5D%5Bis_image%5D=true&select%5Battachments%5D%5Btake%5D=100&select%5Battachments%5D%5BorderBy%5D%5Bcreated_at%5D=desc&select%5Brendered_description%5D=true&select%5Bdescription%5D=true&select%5Bcreated_at%5D=true&select%5Bstart_date%5D=true&select%5Breactions%5D=true&select%5Bintervals%5D=true&select%5Bcolumn_id%5D=true&select%5Bpriority%5D=true&select%5Bdue_date%5D=true&select%5Bcolumn%5D=true&select%5Btitle%5D=true&select%5Border%5D=true&select%5Bcolor%5D=true&where%5Bid%5D=task_id&where%5BAND%5D%5B0%5D%5BOR%5D%5B0%5D%5Bto_delete%5D=false&where%5BAND%5D%5B0%5D%5BOR%5D%5B1%5D%5Bto_delete%5D=null',
86
+ )
87
+ })
88
+
89
+ it('should handle empty objects correctly', () => {
90
+ const params = {}
91
+ const result = encodeQueryParams(params)
92
+ expect(result).toBe('')
93
+ })
94
+
95
+ it('should handle null values correctly', () => {
96
+ const params = {
97
+ id: null,
98
+ name: 'test',
99
+ }
100
+ const result = encodeQueryParams(params)
101
+ expect(result).toBe('id=null&name=test')
102
+ })
103
+
104
+ it('should handle boolean values correctly', () => {
105
+ const params = {
106
+ isActive: true,
107
+ isDeleted: false,
108
+ }
109
+ const result = encodeQueryParams(params)
110
+ expect(result).toBe('isActive=true&isDeleted=false')
111
+ })
112
+
113
+ it('should handle nested arrays correctly', () => {
114
+ const params = {
115
+ filters: [
116
+ {
117
+ key: 'age',
118
+ values: [20, 30, 40],
119
+ },
120
+ ],
121
+ }
122
+ const result = encodeQueryParams(params)
123
+ expect(result).toBe(
124
+ 'filters%5B0%5D%5Bkey%5D=age&filters%5B0%5D%5Bvalues%5D%5B0%5D=20&filters%5B0%5D%5Bvalues%5D%5B1%5D=30&filters%5B0%5D%5Bvalues%5D%5B2%5D=40',
125
+ )
126
+ })
127
+
128
+ it('should handle complex nested arrays and objects', () => {
129
+ const params = {
130
+ select: {
131
+ id: true,
132
+ name: true,
133
+ details: {
134
+ address: {
135
+ street: 'Main St',
136
+ city: 'Metropolis',
137
+ },
138
+ phoneNumbers: [
139
+ {
140
+ type: 'home',
141
+ number: '123-456-7890',
142
+ },
143
+ {
144
+ type: 'work',
145
+ number: '098-765-4321',
146
+ },
147
+ ],
148
+ },
149
+ },
150
+ }
151
+ const result = encodeQueryParams(params)
152
+ expect(result).toBe(
153
+ 'select%5Bid%5D=true&select%5Bname%5D=true&select%5Bdetails%5D%5Baddress%5D%5Bstreet%5D=Main%20St&select%5Bdetails%5D%5Baddress%5D%5Bcity%5D=Metropolis&select%5Bdetails%5D%5BphoneNumbers%5D%5B0%5D%5Btype%5D=home&select%5Bdetails%5D%5BphoneNumbers%5D%5B0%5D%5Bnumber%5D=123-456-7890&select%5Bdetails%5D%5BphoneNumbers%5D%5B1%5D%5Btype%5D=work&select%5Bdetails%5D%5BphoneNumbers%5D%5B1%5D%5Bnumber%5D=098-765-4321',
154
+ )
155
+ })
156
+
157
+ it('should handle edge cases correctly', () => {
158
+ const params = {
159
+ select: {
160
+ id: '',
161
+ name: null,
162
+ details: {
163
+ address: {
164
+ street: undefined,
165
+ city: 'Metropolis',
166
+ },
167
+ },
168
+ },
169
+ }
170
+ const result = encodeQueryParams(params)
171
+ expect(result).toBe(
172
+ 'select%5Bid%5D=&select%5Bname%5D=null&select%5Bdetails%5D%5Baddress%5D%5Bcity%5D=Metropolis',
173
+ )
174
+ })
175
+
176
+ it('should handle multiple nested levels correctly', () => {
177
+ const params = {
178
+ level1: {
179
+ level2: {
180
+ level3: {
181
+ level4: {
182
+ key: 'value',
183
+ },
184
+ },
185
+ },
186
+ },
187
+ }
188
+ const result = encodeQueryParams(params)
189
+ expect(result).toBe(
190
+ 'level1%5Blevel2%5D%5Blevel3%5D%5Blevel4%5D%5Bkey%5D=value',
191
+ )
192
+ })
193
+
194
+ it('should handle empty strings and null values correctly', () => {
195
+ const params = {
196
+ key1: '',
197
+ key2: null,
198
+ key3: 'value',
199
+ }
200
+ const result = encodeQueryParams(params)
201
+ expect(result).toBe('key1=&key2=null&key3=value')
202
+ })
203
+
204
+ it('should encode special characters correctly', () => {
205
+ const params = {
206
+ name: "O'Reilly & Sons",
207
+ description: '20% discount!',
208
+ }
209
+ const result = encodeQueryParams(params)
210
+ expect(result).toBe(
211
+ 'name=O%27Reilly%20%26%20Sons&description=20%25%20discount%21',
212
+ )
213
+ })
214
+
215
+ it('should handle empty arrays correctly', () => {
216
+ const params = {
217
+ filters: [],
218
+ }
219
+ const result = encodeQueryParams(params)
220
+ expect(result).toBe('filters%5B%5D=')
221
+ })
222
+
223
+ it('should encode only special characters correctly', () => {
224
+ const params = {
225
+ special: '!@#$%^&*()_+{}|:"<>?[]\\;\',./`~',
226
+ }
227
+ const result = encodeQueryParams(params)
228
+ expect(result).toBe(
229
+ 'special=%21%40%23%24%25%5E%26%2A%28%29_%2B%7B%7D%7C%3A%22%3C%3E%3F%5B%5D%5C%3B%27%2C.%2F%60%7E',
230
+ )
231
+ })
232
+
233
+ it('should encode repeated special characters correctly', () => {
234
+ const params = {
235
+ special: '!!!@@@###$$$',
236
+ }
237
+ const result = encodeQueryParams(params)
238
+ expect(result).toBe('special=%21%21%21%40%40%40%23%23%23%24%24%24')
239
+ })
240
+
241
+ it('should encode special characters in keys correctly', () => {
242
+ const params = {
243
+ 'sp!ci@l': 'value',
244
+ 'key&with=special?chars': 'another value',
245
+ }
246
+ const result = encodeQueryParams(params)
247
+ expect(result).toBe(
248
+ 'sp%21ci%40l=value&key%26with%3Dspecial%3Fchars=another%20value',
249
+ )
250
+ })
251
+
252
+ it('should handle arrays with mixed types correctly', () => {
253
+ const params = {
254
+ mixedArray: [1, 'two', { three: 3 }],
255
+ }
256
+ const result = encodeQueryParams(params)
257
+ expect(result).toBe(
258
+ 'mixedArray%5B0%5D=1&mixedArray%5B1%5D=two&mixedArray%5B2%5D%5Bthree%5D=3',
259
+ )
260
+ })
261
+
262
+ it('should handle boolean and null values in nested objects correctly', () => {
263
+ const params = {
264
+ nested: {
265
+ flag: true,
266
+ notSet: null,
267
+ },
268
+ }
269
+ const result = encodeQueryParams(params)
270
+ expect(result).toBe('nested%5Bflag%5D=true&nested%5BnotSet%5D=null')
271
+ })
272
+
273
+ it('should handle empty strings in nested objects correctly', () => {
274
+ const params = {
275
+ nested: {
276
+ emptyString: '',
277
+ validString: 'value',
278
+ },
279
+ }
280
+ const result = encodeQueryParams(params)
281
+ expect(result).toBe(
282
+ 'nested%5BemptyString%5D=&nested%5BvalidString%5D=value',
283
+ )
284
+ })
285
+
286
+ it('should handle deeply nested structures correctly', () => {
287
+ const params = {
288
+ level1: {
289
+ level2: {
290
+ level3: {
291
+ level4: {
292
+ level5: 'value',
293
+ },
294
+ },
295
+ },
296
+ },
297
+ }
298
+ const result = encodeQueryParams(params)
299
+ expect(result).toBe(
300
+ 'level1%5Blevel2%5D%5Blevel3%5D%5Blevel4%5D%5Blevel5%5D=value',
301
+ )
302
+ })
303
+ })
@@ -0,0 +1,44 @@
1
+ import { isObject } from './misc'
2
+
3
+ /**
4
+ * Encodes query parameters recursively, skipping undefined values.
5
+ * @param {Record<string, unknown>} params - The query parameters to encode.
6
+ * @returns {string} The encoded query string.
7
+ */
8
+ export const encodeQueryParams = (params: Record<string, unknown>): string => {
9
+ const customEncodeURIComponent = (str: string): string => {
10
+ return encodeURIComponent(str)
11
+ .replace(
12
+ /[!'()*~]/g,
13
+ (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
14
+ )
15
+ .replace(/%20/g, '%20') // Encode spaces as %20
16
+ }
17
+
18
+ const encode = (key: string, value: unknown): string => {
19
+ if (value === undefined) {
20
+ return ''
21
+ }
22
+ if (Array.isArray(value)) {
23
+ if (value.length === 0) {
24
+ return `${customEncodeURIComponent(key)}%5B%5D=`
25
+ }
26
+ return value
27
+ .map((v, i) => encode(`${key}[${i}]`, v))
28
+ .filter(Boolean)
29
+ .join('&')
30
+ }
31
+ if (isObject(value)) {
32
+ return Object.entries(value)
33
+ .map(([k, v]) => encode(`${key}[${k}]`, v))
34
+ .filter(Boolean)
35
+ .join('&')
36
+ }
37
+ return `${customEncodeURIComponent(key)}=${customEncodeURIComponent(String(value))}`
38
+ }
39
+
40
+ return Object.entries(params)
41
+ .map(([k, v]) => encode(k, v))
42
+ .filter(Boolean)
43
+ .join('&')
44
+ }
@@ -0,0 +1,62 @@
1
+ import { isJsonString, safeJSONparse, isObject } from './misc'
2
+
3
+ describe('misc.ts', () => {
4
+ describe('isJsonString', () => {
5
+ it('should return true for valid JSON string', () => {
6
+ expect(isJsonString('{"name":"John"}')).toBe(true)
7
+ })
8
+
9
+ it('should return false for invalid JSON string', () => {
10
+ expect(isJsonString('{"name": "John"')).toBe(false) // Missing closing brace
11
+ })
12
+
13
+ it('should return false for non-string input', () => {
14
+ expect(isJsonString(123)).toBe(false)
15
+ expect(isJsonString({ name: 'John' })).toBe(false)
16
+ expect(isJsonString(null)).toBe(false)
17
+ expect(isJsonString(undefined)).toBe(false)
18
+ })
19
+ })
20
+ describe('safeJSONparse', () => {
21
+ it('should parse valid JSON string', () => {
22
+ expect(safeJSONparse('{"name":"John"}')).toEqual({ name: 'John' })
23
+ })
24
+
25
+ it('should return false for string "false"', () => {
26
+ expect(safeJSONparse('false')).toBe(false)
27
+ })
28
+
29
+ it('should return undefined for string "undefined"', () => {
30
+ expect(safeJSONparse('undefined')).toBeUndefined()
31
+ })
32
+
33
+ it('should return null for string "null"', () => {
34
+ expect(safeJSONparse('null')).toBeNull()
35
+ })
36
+
37
+ it('should return original data for non-JSON string', () => {
38
+ expect(safeJSONparse('Hello World')).toBe('Hello World')
39
+ })
40
+
41
+ it('should return original data for non-string input', () => {
42
+ expect(safeJSONparse(123)).toBe(123)
43
+ expect(safeJSONparse({ name: 'John' })).toEqual({ name: 'John' })
44
+ expect(safeJSONparse(null)).toBe(null)
45
+ expect(safeJSONparse(undefined)).toBe(undefined)
46
+ })
47
+ })
48
+ describe('isObject', () => {
49
+ it('should return true for objects', () => {
50
+ expect(isObject({})).toBe(true)
51
+ expect(isObject({ name: 'John' })).toBe(true)
52
+ })
53
+
54
+ it('should return false for non-objects', () => {
55
+ expect(isObject('Hello World')).toBe(false)
56
+ expect(isObject(123)).toBe(false)
57
+ expect(isObject(null)).toBe(false)
58
+ expect(isObject(undefined)).toBe(false)
59
+ expect(isObject([])).toBe(false) // Arrays are not considered objects in this context
60
+ })
61
+ })
62
+ })
@@ -0,0 +1,25 @@
1
+ export function isJsonString(str: string | unknown): boolean {
2
+ if (typeof str !== 'string') {
3
+ return false
4
+ }
5
+
6
+ try {
7
+ JSON.parse(str)
8
+ } catch (e: unknown) {
9
+ return false
10
+ }
11
+ return true
12
+ }
13
+
14
+ export function safeJSONparse<T>(
15
+ data: unknown,
16
+ ): T | boolean | undefined | null {
17
+ if (data === 'false') return false
18
+ if (data === 'undefined') return undefined
19
+ if (data === 'null') return null
20
+ return isJsonString(data) ? JSON.parse(data as string) : data
21
+ }
22
+
23
+ export const isObject = (value: unknown): value is Record<string, unknown> => {
24
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
25
+ }