prisma-generator-express 1.0.4 → 1.0.5

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 (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +180 -0
  3. package/dist/bin.js.map +1 -0
  4. package/dist/constants.js +5 -0
  5. package/dist/constants.js.map +1 -0
  6. package/dist/generator.js.map +1 -0
  7. package/dist/helpers/genEnum.js +9 -0
  8. package/dist/helpers/genEnum.js.map +1 -0
  9. package/dist/helpers/generateAggregate.js +50 -0
  10. package/dist/helpers/generateAggregate.js.map +1 -0
  11. package/dist/helpers/generateCount.js +50 -0
  12. package/dist/helpers/generateCount.js.map +1 -0
  13. package/dist/helpers/generateCreate.js +51 -0
  14. package/dist/helpers/generateCreate.js.map +1 -0
  15. package/dist/helpers/generateCreateMany.js +51 -0
  16. package/dist/helpers/generateCreateMany.js.map +1 -0
  17. package/dist/helpers/generateDelete.js +52 -0
  18. package/dist/helpers/generateDelete.js.map +1 -0
  19. package/dist/helpers/generateDeleteMany.js +50 -0
  20. package/dist/helpers/generateDeleteMany.js.map +1 -0
  21. package/dist/helpers/generateFindFirst.js +61 -0
  22. package/dist/helpers/generateFindFirst.js.map +1 -0
  23. package/dist/helpers/generateFindMany.js +61 -0
  24. package/dist/helpers/generateFindMany.js.map +1 -0
  25. package/dist/helpers/generateFindUnique copy.js +49 -0
  26. package/dist/helpers/generateFindUnique copy.js.map +1 -0
  27. package/dist/helpers/generateFindUnique.js +61 -0
  28. package/dist/helpers/generateFindUnique.js.map +1 -0
  29. package/dist/helpers/generateGroupBy.js +50 -0
  30. package/dist/helpers/generateGroupBy.js.map +1 -0
  31. package/dist/helpers/generateImportPrismaStatement.js +26 -0
  32. package/dist/helpers/generateImportPrismaStatement.js.map +1 -0
  33. package/dist/helpers/generatePrismaImport.js +2 -0
  34. package/dist/helpers/generatePrismaImport.js.map +1 -0
  35. package/dist/helpers/generateRouteFile.js +181 -0
  36. package/dist/helpers/generateRouteFile.js.map +1 -0
  37. package/dist/helpers/generateUpdate.js +55 -0
  38. package/dist/helpers/generateUpdate.js.map +1 -0
  39. package/dist/helpers/generateUpdateMany.js +52 -0
  40. package/dist/helpers/generateUpdateMany.js.map +1 -0
  41. package/dist/helpers/generateUpsert.js +52 -0
  42. package/dist/helpers/generateUpsert.js.map +1 -0
  43. package/dist/utils/formatFile.js +26 -0
  44. package/dist/utils/formatFile.js.map +1 -0
  45. package/dist/utils/getGeneratorOptions.js +14 -0
  46. package/dist/utils/getGeneratorOptions.js.map +1 -0
  47. package/dist/utils/writeFileSafely.js +21 -0
  48. package/dist/utils/writeFileSafely.js.map +1 -0
  49. package/package.json +8 -4
  50. package/src/bin.ts +2 -0
  51. package/src/constants.ts +1 -0
  52. package/src/generator.ts +174 -0
  53. package/src/helpers/generateAggregate.ts +58 -0
  54. package/src/helpers/generateCount.ts +58 -0
  55. package/src/helpers/generateCreate.ts +58 -0
  56. package/src/helpers/generateCreateMany.ts +58 -0
  57. package/src/helpers/generateDelete.ts +60 -0
  58. package/src/helpers/generateDeleteMany.ts +58 -0
  59. package/src/helpers/generateFindFirst.ts +68 -0
  60. package/src/helpers/generateFindMany.ts +68 -0
  61. package/src/helpers/generateFindUnique.ts +68 -0
  62. package/src/helpers/generateGroupBy.ts +58 -0
  63. package/src/helpers/generateImportPrismaStatement.ts +38 -0
  64. package/src/helpers/generateRouteFile.ts +183 -0
  65. package/src/helpers/generateUpdate.ts +62 -0
  66. package/src/helpers/generateUpdateMany.ts +59 -0
  67. package/src/helpers/generateUpsert.ts +60 -0
  68. package/src/utils/formatFile.ts +22 -0
  69. package/src/utils/writeFileSafely.ts +28 -0
@@ -0,0 +1,68 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that includes conditional output validation with Zod.
5
+ * This version dynamically includes the correct type for the query parameter based on the Prisma model.
6
+ * @param options - The options containing the model name and the import statement for Prisma types.
7
+ * @returns {string} - The generated middleware function as a string.
8
+ */
9
+ export const generateFindFirstFunction = (options: {
10
+ model: DMMF.Model
11
+ prismaImportStatement: string
12
+ }): string => {
13
+ const { model, prismaImportStatement } = options
14
+ const modelName = model.name
15
+ const functionName = `${modelName}FindFirst`
16
+ const queryTypeName = `Prisma.${modelName}FindFirstArgs`
17
+
18
+ return `
19
+ ${prismaImportStatement.replace('{ Prisma }', `{ Prisma, ${modelName} }`)}
20
+ import { Request, Response, NextFunction } from 'express'
21
+ import {
22
+ RequestHandler,
23
+ ParamsDictionary,
24
+ } from 'express-serve-static-core'
25
+ import { ParsedQs } from 'qs';
26
+ import { ZodTypeAny } from 'zod';
27
+
28
+ export interface FindFirstRequest extends Request {
29
+ prisma: PrismaClient;
30
+ query: ${queryTypeName} & ParsedQs;
31
+ outputValidation?: ZodTypeAny;
32
+ omitOutputValidation?: boolean;
33
+ passToNext?: boolean;
34
+ locals: {
35
+ data?: ${modelName} | null
36
+ }
37
+ }
38
+ export type FindFirstMiddleware = RequestHandler<ParamsDictionary, any, any, ${queryTypeName} & ParsedQs, Record<string, any>>
39
+
40
+ export async function ${functionName}(req: FindFirstRequest, res: Response, next: NextFunction) {
41
+ try {
42
+ if (!req.outputValidation && !req.omitOutputValidation) {
43
+ throw new Error('Output validation schema or omission flag must be provided.');
44
+ }
45
+
46
+ const data = await req.prisma.${modelName.toLowerCase()}.findFirst(req.query as ${queryTypeName});
47
+ if (req.passToNext) {
48
+ req.locals.data = data;
49
+ next();
50
+ } else if (!req.omitOutputValidation && req.outputValidation) {
51
+ const validationResult = req.outputValidation.safeParse(data);
52
+ if (validationResult.success) {
53
+ res.status(200).json(validationResult.data);
54
+ } else {
55
+ res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
56
+ }
57
+ } else if (!req.omitOutputValidation) {
58
+ throw new Error('Output validation schema must be provided unless explicitly omitted. Attach omitOutputValidation = true to request to suppress this error.');
59
+ } else {
60
+ res.status(200).json(data);
61
+ }
62
+ } catch (error) {
63
+ console.error('Error in handling request:', error);
64
+ res.status(500).json({ error: error.message });
65
+ next(error);
66
+ }
67
+ }`
68
+ }
@@ -0,0 +1,68 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles multiple record retrieval with optional output validation using Zod.
5
+ * This version dynamically includes the correct type for the query parameter based on the Prisma model.
6
+ * @param options - The options containing the model name and the import statement for Prisma types.
7
+ * @returns {string} - The generated middleware function as a string.
8
+ */
9
+ export const generateFindManyFunction = (options: {
10
+ model: DMMF.Model
11
+ prismaImportStatement: string
12
+ }): string => {
13
+ const { model, prismaImportStatement } = options
14
+ const modelName = model.name
15
+ const functionName = `${modelName}FindMany`
16
+ const queryTypeName = `Prisma.${modelName}FindManyArgs`
17
+
18
+ return `
19
+ ${prismaImportStatement.replace('{ Prisma }', `{ Prisma, ${modelName} }`)}
20
+ import { Request, Response, NextFunction } from 'express'
21
+ import {
22
+ RequestHandler,
23
+ ParamsDictionary,
24
+ } from 'express-serve-static-core'
25
+ import { ParsedQs } from 'qs';
26
+ import { ZodTypeAny } from 'zod';
27
+
28
+ export interface FindManyRequest extends Request {
29
+ prisma: PrismaClient;
30
+ query: ${queryTypeName} & ParsedQs;
31
+ outputValidation?: ZodTypeAny;
32
+ omitOutputValidation?: boolean;
33
+ passToNext?: boolean;
34
+ locals: {
35
+ data?: ${modelName}[]
36
+ }
37
+ }
38
+ export type FindManyMiddleware = RequestHandler<ParamsDictionary, any, any, ${queryTypeName} & ParsedQs, Record<string, any>>
39
+
40
+ export async function ${functionName}(req: FindManyRequest, res: Response, next: NextFunction) {
41
+ try {
42
+ if (!req.outputValidation && !req.omitOutputValidation) {
43
+ throw new Error('Output validation schema or omission flag must be provided.');
44
+ }
45
+
46
+ const data = await req.prisma.${modelName.toLowerCase()}.findMany(req.query as ${queryTypeName});
47
+ if (req.passToNext) {
48
+ req.locals.data = data;
49
+ next();
50
+ } else if (!req.omitOutputValidation && req.outputValidation) {
51
+ const validationResult = req.outputValidation.safeParse(data);
52
+ if (validationResult.success) {
53
+ res.status(200).json(validationResult.data);
54
+ } else {
55
+ res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
56
+ }
57
+ } else if (!req.omitOutputValidation) {
58
+ throw new Error('Output validation schema must be provided unless explicitly omitted. Attach omitOutputValidation = true to request to suppress this error.');
59
+ } else {
60
+ res.status(200).json(data);
61
+ }
62
+ } catch (error) {
63
+ console.error('Error in handling request:', error);
64
+ res.status(500).json({ error: error.message });
65
+ next(error);
66
+ }
67
+ }`
68
+ }
@@ -0,0 +1,68 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that includes conditional output validation with Zod.
5
+ * This version dynamically includes the correct type for the query parameter based on the Prisma model.
6
+ * @param options - The options containing the model name and the import statement for Prisma types.
7
+ * @returns {string} - The generated middleware function as a string.
8
+ */
9
+ export const generateFindUniqueFunction = (options: {
10
+ model: DMMF.Model
11
+ prismaImportStatement: string
12
+ }): string => {
13
+ const { model, prismaImportStatement } = options
14
+ const modelName = model.name
15
+ const functionName = `${modelName}FindUnique`
16
+ const queryTypeName = `Prisma.${modelName}FindUniqueArgs`
17
+
18
+ return `
19
+ ${prismaImportStatement.replace('{ Prisma }', `{ Prisma, ${modelName} }`)}
20
+ import { Request, Response, NextFunction } from 'express'
21
+ import {
22
+ RequestHandler,
23
+ ParamsDictionary,
24
+ } from 'express-serve-static-core'
25
+ import { ParsedQs } from 'qs';
26
+ import { ZodTypeAny } from 'zod';
27
+
28
+ export interface FindUniqueRequest extends Request {
29
+ prisma: PrismaClient;
30
+ query: ${queryTypeName} & ParsedQs;
31
+ outputValidation?: ZodTypeAny;
32
+ omitOutputValidation?: boolean;
33
+ passToNext?: boolean;
34
+ locals: {
35
+ data?: ${modelName} | null
36
+ }
37
+ }
38
+ export type FindUniqueMiddleware = RequestHandler<ParamsDictionary, any, any, ${queryTypeName} & ParsedQs, Record<string, any>>
39
+
40
+ export async function ${functionName}(req: FindUniqueRequest, res: Response, next: NextFunction) {
41
+ try {
42
+ if (!req.outputValidation && !req.omitOutputValidation) {
43
+ throw new Error('Output validation schema or omission flag must be provided.');
44
+ }
45
+
46
+ const data = await req.prisma.${modelName.toLowerCase()}.findUnique(req.query as ${queryTypeName});
47
+ if (req.passToNext) {
48
+ req.locals.data = data;
49
+ next();
50
+ } else if (!req.omitOutputValidation && req.outputValidation) {
51
+ const validationResult = req.outputValidation.safeParse(data);
52
+ if (validationResult.success) {
53
+ res.status(200).json(validationResult.data);
54
+ } else {
55
+ res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
56
+ }
57
+ } else if (!req.omitOutputValidation) {
58
+ throw new Error('Output validation schema must be provided unless explicitly omitted. Attach omitOutputValidation = true to request to suppress this error.');
59
+ } else {
60
+ res.status(200).json(data);
61
+ }
62
+ } catch (error) {
63
+ console.error('Error in handling request:', error);
64
+ res.status(500).json({ error: error.message });
65
+ next(error);
66
+ }
67
+ }`
68
+ }
@@ -0,0 +1,58 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles groupBy queries
5
+ * and includes conditional output validation with Zod.
6
+ * This version dynamically includes the correct type for the arguments based on the Prisma model.
7
+ * @param options - The options containing the model name and the import statement for Prisma types.
8
+ * @returns {string} - The generated middleware function as a string.
9
+ */
10
+ export const generateGroupByFunction = (options: {
11
+ model: DMMF.Model
12
+ prismaImportStatement: string
13
+ }): string => {
14
+ const { model, prismaImportStatement } = options
15
+ const modelName = model.name
16
+ const functionName = `${modelName}GroupBy`
17
+ const argsTypeName = `Prisma.${modelName}GroupByArgs`
18
+
19
+ return `
20
+ ${prismaImportStatement}
21
+ import { Request, Response, NextFunction } from 'express';
22
+ import { RequestHandler, ParamsDictionary } from 'express-serve-static-core'
23
+ import { ZodTypeAny } from 'zod';
24
+
25
+ interface GroupByRequest extends Request {
26
+ prisma: PrismaClient;
27
+ body: ${argsTypeName};
28
+ outputValidation?: ZodTypeAny;
29
+ omitOutputValidation?: boolean;
30
+ }
31
+
32
+ export type GroupByMiddleware = RequestHandler<ParamsDictionary, any, ${argsTypeName}, Record<string, any>>;
33
+
34
+ export async function ${functionName}(req: GroupByRequest, res: Response, next: NextFunction) {
35
+ try {
36
+ if (!req.outputValidation && !req.omitOutputValidation) {
37
+ throw new Error('Output validation schema or omission flag must be provided.');
38
+ }
39
+
40
+ const result = await req.prisma.${modelName.toLowerCase()}.groupBy(req.body);
41
+
42
+ if (!req.omitOutputValidation && req.outputValidation) {
43
+ const validationResult = req.outputValidation.safeParse(result);
44
+ if (validationResult.success) {
45
+ res.status(200).json(validationResult.data);
46
+ } else {
47
+ res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
48
+ }
49
+ } else {
50
+ res.status(200).json(result);
51
+ }
52
+ } catch (error) {
53
+ console.error('Error in handling groupBy request:', error);
54
+ res.status(500).json({ error: error.message });
55
+ next(error);
56
+ }
57
+ }`
58
+ }
@@ -0,0 +1,38 @@
1
+ import { GeneratorOptions } from '@prisma/generator-helper'
2
+ import path from 'path'
3
+
4
+ interface ImportPrismaStatementOptions {
5
+ outputPath: string
6
+ }
7
+
8
+ function getImportGeneratorOptions(
9
+ options: GeneratorOptions,
10
+ ): ImportPrismaStatementOptions {
11
+ const clientGenerator = options.otherGenerators.find(
12
+ (gen) => gen.name === 'client',
13
+ )
14
+
15
+ if (!clientGenerator || !clientGenerator.output?.value) {
16
+ throw new Error('Prisma client generator not found.')
17
+ }
18
+
19
+ const modelDirPath = path.join(
20
+ options.generator.output?.value!,
21
+ 'modelFolder', // workaround for saving with /modelName/operation structure
22
+ )
23
+ const clientOutputPath = clientGenerator.output.value
24
+
25
+ const relativeImportPath = path.relative(modelDirPath, clientOutputPath)
26
+
27
+ return {
28
+ outputPath: relativeImportPath.split(path.sep).join(path.posix.sep),
29
+ }
30
+ }
31
+
32
+ export function generateImportPrismaStatement(
33
+ generatorOptions: GeneratorOptions,
34
+ ): string {
35
+ const options = getImportGeneratorOptions(generatorOptions)
36
+ // console.log('options.outputPath :>> ', options.outputPath)
37
+ return `import type { Prisma } from '${options.outputPath}';\nimport type { PrismaClient } from '${options.outputPath}';\n`
38
+ }
@@ -0,0 +1,183 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ export function generateRouterFunction({
4
+ model,
5
+ }: {
6
+ model: DMMF.Model
7
+ }): string {
8
+ const modelName = model.name
9
+ const routerFunctionName = `${modelName}Router`
10
+
11
+ return `
12
+ import express, { RequestHandler } from 'express';
13
+ import { ${modelName}FindFirst, type FindFirstMiddleware } from './${modelName}FindFirst';
14
+ import { ${modelName}FindMany, type FindManyMiddleware } from './${modelName}FindMany';
15
+ import { ${modelName}FindUnique, type FindUniqueMiddleware } from './${modelName}FindUnique';
16
+ import { ${modelName}Create, type CreateMiddleware } from './${modelName}Create';
17
+ import { ${modelName}CreateMany, type CreateManyMiddleware } from './${modelName}CreateMany';
18
+ import { ${modelName}Update, type UpdateMiddleware } from './${modelName}Update';
19
+ import { ${modelName}UpdateMany, type UpdateManyMiddleware } from './${modelName}UpdateMany';
20
+ import { ${modelName}Upsert, type UpsertMiddleware } from './${modelName}Upsert';
21
+ import { ${modelName}Delete, type DeleteMiddleware } from './${modelName}Delete';
22
+ import { ${modelName}DeleteMany, type DeleteManyMiddleware } from './${modelName}DeleteMany';
23
+ import { ${modelName}Aggregate, type AggregateMiddleware } from './${modelName}Aggregate';
24
+ import { ${modelName}Count, type CountMiddleware } from './${modelName}Count';
25
+ import { ${modelName}GroupBy, type GroupByMiddleware } from './${modelName}GroupBy';
26
+
27
+ interface RouteConfig {
28
+ findFirstMiddleware?: FindFirstMiddleware[]
29
+ findFirstNextMiddleware?: RequestHandler[]
30
+
31
+ findManyMiddleware?: FindManyMiddleware[]
32
+ findManyNextMiddleware?: RequestHandler[]
33
+
34
+ findUniqueMiddleware?: FindUniqueMiddleware[]
35
+ findUniqueNextMiddleware?: RequestHandler[]
36
+
37
+ createMiddleware?: CreateMiddleware[]
38
+ createNextMiddleware?: RequestHandler[]
39
+
40
+ createManyMiddleware?: CreateManyMiddleware[]
41
+ createManyNextMiddleware?: RequestHandler[]
42
+
43
+ updateMiddleware?: UpdateMiddleware[]
44
+ updateNextMiddleware?: RequestHandler[]
45
+
46
+ updateManyMiddleware?: UpdateManyMiddleware[]
47
+ updateManyNextMiddleware?: RequestHandler[]
48
+
49
+ upsertMiddleware?: UpsertMiddleware[]
50
+ upsertNextMiddleware?: RequestHandler[]
51
+
52
+ deleteMiddleware?: DeleteMiddleware[]
53
+ deleteNextMiddleware?: RequestHandler[]
54
+
55
+ deleteManyMiddleware?: DeleteManyMiddleware[]
56
+ deleteManyNextMiddleware?: RequestHandler[]
57
+
58
+ aggregateMiddleware?: AggregateMiddleware[]
59
+ aggregateNextMiddleware?: RequestHandler[]
60
+
61
+ countMiddleware?: CountMiddleware[]
62
+ countNextMiddleware?: RequestHandler[]
63
+
64
+ groupByMiddleware?: GroupByMiddleware[]
65
+ groupByNextMiddleware?: RequestHandler[]
66
+ }
67
+
68
+ /**
69
+ * Generates an Express router for ${modelName} model.
70
+ * @param config Contains optional middleware to enable routes.
71
+ * @returns {express.Router}
72
+ */
73
+ export function ${routerFunctionName}(config: RouteConfig) {
74
+ const router = express.Router();
75
+
76
+ if (config?.findFirstMiddleware && config?.findFirstMiddleware.length) {
77
+ const middlewares = [...config.findFirstMiddleware, ${modelName}FindFirst]
78
+ if (config.findFirstNextMiddleware) {
79
+ middlewares.push(...config.findFirstNextMiddleware);
80
+ }
81
+ router.get('/first', ...middlewares as FindFirstMiddleware[]);
82
+ }
83
+
84
+ if (config?.findManyMiddleware && config?.findManyMiddleware.length) {
85
+ const middlewares = [...config.findManyMiddleware, ${modelName}FindMany]
86
+ if (config.findManyNextMiddleware) {
87
+ middlewares.push(...config.findManyNextMiddleware);
88
+ }
89
+ router.get('/', ...middlewares as FindManyMiddleware[]);
90
+ }
91
+
92
+ if (config?.findUniqueMiddleware && config?.findUniqueMiddleware.length) {
93
+ const middlewares = [...config.findUniqueMiddleware, ${modelName}FindUnique]
94
+ if (config.findUniqueNextMiddleware) {
95
+ middlewares.push(...config.findUniqueNextMiddleware);
96
+ }
97
+ router.get('/:id', ...middlewares as FindUniqueMiddleware[]);
98
+ }
99
+
100
+ if (config?.createMiddleware && config?.createMiddleware.length) {
101
+ const middlewares = [...config.createMiddleware, ${modelName}Create]
102
+ if (config.createNextMiddleware) {
103
+ middlewares.push(...config.createNextMiddleware);
104
+ }
105
+ router.post('/', ...middlewares);
106
+ }
107
+
108
+ if (config?.createManyMiddleware && config?.createManyMiddleware.length) {
109
+ const middlewares = [...config.createManyMiddleware, ${modelName}CreateMany]
110
+ if (config.createManyNextMiddleware) {
111
+ middlewares.push(...config.createManyNextMiddleware);
112
+ }
113
+ router.post('/many', ...middlewares);
114
+ }
115
+
116
+ if (config?.updateMiddleware && config?.updateMiddleware.length) {
117
+ const middlewares = [...config.updateMiddleware, ${modelName}Update]
118
+ if (config.updateNextMiddleware) {
119
+ middlewares.push(...config.updateNextMiddleware);
120
+ }
121
+ router.put('/', ...middlewares);
122
+ }
123
+
124
+ if (config?.updateManyMiddleware && config?.updateManyMiddleware.length) {
125
+ const middlewares = [...config.updateManyMiddleware, ${modelName}UpdateMany]
126
+ if (config.updateManyNextMiddleware) {
127
+ middlewares.push(...config.updateManyNextMiddleware);
128
+ }
129
+ router.put('/many', ...middlewares);
130
+ }
131
+
132
+ if (config?.upsertMiddleware && config?.upsertMiddleware.length) {
133
+ const middlewares = [...config.upsertMiddleware, ${modelName}Upsert]
134
+ if (config.upsertNextMiddleware) {
135
+ middlewares.push(...config.upsertNextMiddleware);
136
+ }
137
+ router.patch('/', ...middlewares);
138
+ }
139
+
140
+ if (config?.deleteMiddleware && config?.deleteMiddleware.length) {
141
+ const middlewares = [...config.deleteMiddleware, ${modelName}Delete]
142
+ if (config.deleteNextMiddleware) {
143
+ middlewares.push(...config.deleteNextMiddleware);
144
+ }
145
+ router.delete('/', ...middlewares);
146
+ }
147
+
148
+ if (config?.deleteManyMiddleware && config?.deleteManyMiddleware.length) {
149
+ const middlewares = [...config.deleteManyMiddleware, ${modelName}DeleteMany]
150
+ if (config.deleteManyNextMiddleware) {
151
+ middlewares.push(...config.deleteManyNextMiddleware);
152
+ }
153
+ router.delete('/many', ...middlewares);
154
+ }
155
+
156
+ if (config?.aggregateMiddleware && config?.aggregateMiddleware.length) {
157
+ const middlewares = [...config.aggregateMiddleware, ${modelName}Aggregate]
158
+ if (config.aggregateNextMiddleware) {
159
+ middlewares.push(...config.aggregateNextMiddleware);
160
+ }
161
+ router.get('/aggregate', ...middlewares);
162
+ }
163
+
164
+ if (config?.countMiddleware && config?.countMiddleware.length) {
165
+ const middlewares = [...config.countMiddleware, ${modelName}Count]
166
+ if (config.countNextMiddleware) {
167
+ middlewares.push(...config.countNextMiddleware);
168
+ }
169
+ router.get('/count', ...middlewares);
170
+ }
171
+
172
+ if (config?.groupByMiddleware && config?.groupByMiddleware.length) {
173
+ const middlewares = [...config.groupByMiddleware, ${modelName}GroupBy]
174
+ if (config.groupByNextMiddleware) {
175
+ middlewares.push(...config.groupByNextMiddleware);
176
+ }
177
+ router.get('/groupby', ...middlewares);
178
+ }
179
+
180
+ return router;
181
+ }
182
+ `
183
+ }
@@ -0,0 +1,62 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles updating records and includes conditional output validation with Zod.
5
+ * This version dynamically includes the correct type for the arguments based on the Prisma model.
6
+ * @param options - The options containing the model name and the import statement for Prisma types.
7
+ * @returns {string} - The generated middleware function as a string.
8
+ */
9
+ export const generateUpdateFunction = (options: {
10
+ model: DMMF.Model
11
+ prismaImportStatement: string
12
+ }): string => {
13
+ const { model, prismaImportStatement } = options
14
+ const modelName = model.name
15
+ const functionName = `${modelName}Update`
16
+ const argsTypeName = `Prisma.${modelName}UpdateArgs`
17
+
18
+ return `
19
+ ${prismaImportStatement}
20
+ import { Request, Response, NextFunction } from 'express';
21
+ import { RequestHandler, ParamsDictionary } from 'express-serve-static-core';
22
+ import { ZodTypeAny } from 'zod';
23
+
24
+ interface UpdateRequest extends Request {
25
+ prisma: PrismaClient;
26
+ body: ${argsTypeName};
27
+ outputValidation?: ZodTypeAny;
28
+ omitOutputValidation?: boolean;
29
+ }
30
+
31
+ export type UpdateMiddleware = RequestHandler<ParamsDictionary, any, ${argsTypeName}, Record<string, any>>
32
+
33
+ export async function ${functionName}(req: UpdateRequest, res: Response, next: NextFunction) {
34
+ try {
35
+ if (!req.outputValidation && !req.omitOutputValidation) {
36
+ throw new Error('Output validation schema or omission flag must be provided.');
37
+ }
38
+
39
+ const data = await req.prisma.${modelName.toLowerCase()}.update({
40
+ where: { id: parseInt(req.params.id) },
41
+ data: req.body
42
+ });
43
+
44
+ if (!req.omitOutputValidation && req.outputValidation) {
45
+ const validationResult = req.outputValidation.safeParse(data);
46
+ if (validationResult.success) {
47
+ res.status(200).json(validationResult.data);
48
+ } else {
49
+ res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
50
+ }
51
+ } else if (!req.omitOutputValidation) {
52
+ throw new Error('Output validation schema must be provided unless explicitly omitted.');
53
+ } else {
54
+ res.status(200).json(data);
55
+ }
56
+ } catch (error) {
57
+ console.error('Error in handling update request:', error);
58
+ res.status(500).json({ error: error.message });
59
+ next(error);
60
+ }
61
+ }`
62
+ }
@@ -0,0 +1,59 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles updating multiple records and includes conditional output validation with Zod.
5
+ * This version dynamically includes the correct type for the arguments based on the Prisma model.
6
+ * @param options - The options containing the model name and the import statement for Prisma types.
7
+ * @returns {string} - The generated middleware function as a string.
8
+ */
9
+ export const generateUpdateManyFunction = (options: {
10
+ model: DMMF.Model
11
+ prismaImportStatement: string
12
+ }): string => {
13
+ const { model, prismaImportStatement } = options
14
+ const modelName = model.name
15
+ const functionName = `${modelName}UpdateMany`
16
+ const argsTypeName = `Prisma.${modelName}UpdateManyArgs`
17
+
18
+ return `
19
+ ${prismaImportStatement}
20
+ import { Request, Response, NextFunction } from 'express';
21
+ import { RequestHandler, ParamsDictionary } from 'express-serve-static-core';
22
+ import { ZodTypeAny } from 'zod';
23
+
24
+ interface UpdateManyRequest extends Request {
25
+ prisma: PrismaClient;
26
+ body: ${argsTypeName};
27
+ outputValidation?: ZodTypeAny;
28
+ omitOutputValidation?: boolean;
29
+ }
30
+
31
+ export type UpdateManyMiddleware = RequestHandler<ParamsDictionary, any, ${argsTypeName}, Record<string, any>>
32
+
33
+ export async function ${functionName}(req: UpdateManyRequest, res: Response, next: NextFunction) {
34
+ try {
35
+ if (!req.outputValidation && !req.omitOutputValidation) {
36
+ throw new Error('Output validation schema or omission flag must be provided.');
37
+ }
38
+
39
+ const data = await req.prisma.${modelName.toLowerCase()}.updateMany(req.body);
40
+
41
+ if (!req.omitOutputValidation && req.outputValidation) {
42
+ const validationResult = req.outputValidation.safeParse(data);
43
+ if (validationResult.success) {
44
+ res.status(200).json({ count: validationResult.data.count });
45
+ } else {
46
+ res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
47
+ }
48
+ } else if (!req.omitOutputValidation) {
49
+ throw new Error('Output validation schema must be provided unless explicitly omitted.');
50
+ } else {
51
+ res.status(200).json({ count: data.count });
52
+ }
53
+ } catch (error) {
54
+ console.error('Error in handling updateMany request:', error);
55
+ res.status(500).json({ error: error.message });
56
+ next(error);
57
+ }
58
+ }`
59
+ }
@@ -0,0 +1,60 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles the upsert operation (create or update)
5
+ * and includes conditional output validation with Zod.
6
+ * This version dynamically includes the correct type for the arguments based on the Prisma model.
7
+ * @param options - The options containing the model name and the import statement for Prisma types.
8
+ * @returns {string} - The generated middleware function as a string.
9
+ */
10
+ export const generateUpsertFunction = (options: {
11
+ model: DMMF.Model
12
+ prismaImportStatement: string
13
+ }): string => {
14
+ const { model, prismaImportStatement } = options
15
+ const modelName = model.name
16
+ const functionName = `${modelName}Upsert`
17
+ const argsTypeName = `Prisma.${modelName}UpsertArgs`
18
+
19
+ return `
20
+ ${prismaImportStatement}
21
+ import { Request, Response, NextFunction } from 'express';
22
+ import { RequestHandler, ParamsDictionary } from 'express-serve-static-core';
23
+ import { ZodTypeAny } from 'zod';
24
+
25
+ interface UpsertRequest extends Request {
26
+ prisma: PrismaClient;
27
+ body: ${argsTypeName};
28
+ outputValidation?: ZodTypeAny;
29
+ omitOutputValidation?: boolean;
30
+ }
31
+
32
+ export type UpsertMiddleware = RequestHandler<ParamsDictionary, any, ${argsTypeName}, Record<string, any>>
33
+
34
+ export async function ${functionName}(req: UpsertRequest, res: Response, next: NextFunction) {
35
+ try {
36
+ if (!req.outputValidation && !req.omitOutputValidation) {
37
+ throw new Error('Output validation schema or omission flag must be provided.');
38
+ }
39
+
40
+ const data = await req.prisma.${modelName.toLowerCase()}.upsert(req.body);
41
+
42
+ if (!req.omitOutputValidation && req.outputValidation) {
43
+ const validationResult = req.outputValidation.safeParse(data);
44
+ if (validationResult.success) {
45
+ res.status(200).json(validationResult.data);
46
+ } else {
47
+ res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
48
+ }
49
+ } else if (!req.omitOutputValidation) {
50
+ throw new Error('Output validation schema must be provided unless explicitly omitted.');
51
+ } else {
52
+ res.status(200).json(data);
53
+ }
54
+ } catch (error) {
55
+ console.error('Error in handling upsert request:', error);
56
+ res.status(500).json({ error: error.message });
57
+ next(error);
58
+ }
59
+ }`
60
+ }