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 @@
1
+ {"version":3,"file":"formatFile.js","sourceRoot":"","sources":["../../src/utils/formatFile.ts"],"names":[],"mappings":";;;;;;AAAA,wDAA+B;AAExB,MAAM,UAAU,GAAG,CAAC,OAAe,EAAmB,EAAE;IAC7D,OAAO,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAC9B,kBAAQ,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE;QACrD,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,GAAG,CAAC,OAAO,CAAC,CAAA;QACd,CAAC;QAED,IAAI,CAAC;YACH,MAAM,SAAS,GAAG,kBAAQ,CAAC,MAAM,CAAC,OAAO,EAAE;gBACzC,GAAG,OAAO;gBACV,MAAM,EAAE,YAAY;aACrB,CAAC,CAAA;YAEF,GAAG,CAAC,SAAS,CAAC,CAAA;QAChB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,KAAK,CAAC,CAAA;QACZ,CAAC;IACH,CAAC,CAAC,CACH,CAAA;AACH,CAAC,CAAA;AAnBY,QAAA,UAAU,cAmBtB"}
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGeneratorOptions = void 0;
4
+ function getGeneratorOptions(options) {
5
+ var _a;
6
+ return {
7
+ isCustomPrismaClientOutputPath: Boolean(options.generator.config.customOutputPath),
8
+ outputPath: ((_a = options.generator.output) === null || _a === void 0 ? void 0 : _a.value) || './generated',
9
+ prismaClientOutputPath: (options.generator.config.clientPath ||
10
+ '@prisma/client'),
11
+ };
12
+ }
13
+ exports.getGeneratorOptions = getGeneratorOptions;
14
+ //# sourceMappingURL=getGeneratorOptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getGeneratorOptions.js","sourceRoot":"","sources":["../../src/utils/getGeneratorOptions.ts"],"names":[],"mappings":";;;AAGA,SAAgB,mBAAmB,CACjC,OAAyB;;IAEzB,OAAO;QACL,8BAA8B,EAAE,OAAO,CACrC,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC,gBAAgB,CAC1C;QACD,UAAU,EAAE,CAAA,MAAA,OAAO,CAAC,SAAS,CAAC,MAAM,0CAAE,KAAK,KAAI,aAAa;QAC5D,sBAAsB,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC,UAAU;YAC1D,gBAAgB,CAAW;KAC9B,CAAA;AACH,CAAC;AAXD,kDAWC"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.writeFileSafely = void 0;
7
+ const promises_1 = __importDefault(require("fs/promises"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const formatFile_1 = require("./formatFile");
10
+ const writeFileSafely = async ({ model, operation, options, content, }) => {
11
+ var _a;
12
+ const fileName = operation === 'index' ? 'index' : `${model.name}${operation}`;
13
+ const filePath = path_1.default.join((_a = options.generator.output) === null || _a === void 0 ? void 0 : _a.value, `${model.name}/${fileName}.ts`);
14
+ console.log('filePath :>> ', filePath);
15
+ await promises_1.default.mkdir(path_1.default.dirname(filePath), {
16
+ recursive: true,
17
+ });
18
+ await promises_1.default.writeFile(filePath, await (0, formatFile_1.formatFile)(content));
19
+ };
20
+ exports.writeFileSafely = writeFileSafely;
21
+ //# sourceMappingURL=writeFileSafely.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writeFileSafely.js","sourceRoot":"","sources":["../../src/utils/writeFileSafely.ts"],"names":[],"mappings":";;;;;;AAAA,2DAA4B;AAC5B,gDAAuB;AACvB,6CAAyC;AAGlC,MAAM,eAAe,GAAG,KAAK,EAAE,EACpC,KAAK,EACL,SAAS,EACT,OAAO,EACP,OAAO,GAMR,EAAE,EAAE;;IACH,MAAM,QAAQ,GAAG,SAAS,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,IAAI,GAAG,SAAS,EAAE,CAAA;IAC9E,MAAM,QAAQ,GAAG,cAAI,CAAC,IAAI,CACxB,MAAA,OAAO,CAAC,SAAS,CAAC,MAAM,0CAAE,KAAM,EAChC,GAAG,KAAK,CAAC,IAAI,IAAI,QAAQ,KAAK,CAC/B,CAAA;IACD,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAA;IACtC,MAAM,kBAAE,CAAC,KAAK,CAAC,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;QACrC,SAAS,EAAE,IAAI;KAChB,CAAC,CAAA;IAEF,MAAM,kBAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAA,uBAAU,EAAC,OAAO,CAAC,CAAC,CAAA;AACzD,CAAC,CAAA;AAtBY,QAAA,eAAe,mBAsB3B"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "prisma-generator-express",
3
3
  "description": "Prisma generator of Express CRUD API",
4
- "version": "1.0.4",
4
+ "version": "1.0.5",
5
5
  "main": "dist/generator.js",
6
6
  "license": "MIT",
7
7
  "bin": {
@@ -15,7 +15,8 @@
15
15
  "dev": "npx tsc -w",
16
16
  "build": "npx tsc",
17
17
  "prepack": "yarn build",
18
- "test": "jest"
18
+ "test": "jest",
19
+ "prepublishOnly": "node copy.js "
19
20
  },
20
21
  "dependencies": {
21
22
  "@prisma/client": "5.14.0",
@@ -36,6 +37,7 @@
36
37
  "prisma": "5.14.0",
37
38
  "semantic-release": "^23.1.1",
38
39
  "ts-jest": "29.1.2",
40
+ "shx": "^0.3.4",
39
41
  "typescript": "5.4.5"
40
42
  },
41
43
  "homepage": "https://github.com/multipliedtwice/prisma-generator-express/blob/master/README.md",
@@ -51,8 +53,10 @@
51
53
  "generator"
52
54
  ],
53
55
  "files": [
54
- "../../../README.md",
55
- "../../../LICENSE"
56
+ "dist/**/*",
57
+ "src/**/*",
58
+ "../../README.md",
59
+ "../../LICENSE"
56
60
  ],
57
61
  "release": {
58
62
  "branches": [
package/src/bin.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import './generator'
@@ -0,0 +1 @@
1
+ export const GENERATOR_NAME = 'prisma-generator-express'
@@ -0,0 +1,174 @@
1
+ import { generatorHandler, GeneratorOptions } from '@prisma/generator-helper'
2
+ import { logger } from '@prisma/sdk'
3
+ import { GENERATOR_NAME } from './constants'
4
+ import { writeFileSafely } from './utils/writeFileSafely'
5
+ import { generateFindUniqueFunction } from './helpers/generateFindUnique'
6
+ import { generateImportPrismaStatement } from './helpers/generateImportPrismaStatement'
7
+ import { generateFindManyFunction } from './helpers/generateFindMany'
8
+ import { generateFindFirstFunction } from './helpers/generateFindFirst'
9
+ import { generateCreateFunction } from './helpers/generateCreate'
10
+ import { generateRouterFunction } from './helpers/generateRouteFile'
11
+ import { generateCreateManyFunction } from './helpers/generateCreateMany'
12
+ import { generateUpdateFunction } from './helpers/generateUpdate'
13
+ import { generateUpdateManyFunction } from './helpers/generateUpdateMany'
14
+ import { generateUpsertFunction } from './helpers/generateUpsert'
15
+ import { generateDeleteFunction } from './helpers/generateDelete'
16
+ import { generateDeleteManyFunction } from './helpers/generateDeleteMany'
17
+ import { generateAggregateFunction } from './helpers/generateAggregate'
18
+ import { generateCountFunction } from './helpers/generateCount'
19
+ import { generateGroupByFunction } from './helpers/generateGroupBy'
20
+
21
+ const { version } = require('../package.json')
22
+
23
+ generatorHandler({
24
+ onManifest() {
25
+ logger.info(`${GENERATOR_NAME}:Registered`)
26
+ return {
27
+ version,
28
+ defaultOutput: '../generated',
29
+ prettyName: GENERATOR_NAME,
30
+ }
31
+ },
32
+ onGenerate: async (options: GeneratorOptions) => {
33
+ const prismaImportStatement = generateImportPrismaStatement(options)
34
+
35
+ options.dmmf.datamodel.models.forEach(async (model) => {
36
+ await writeFileSafely({
37
+ content: generateFindUniqueFunction({
38
+ model,
39
+ prismaImportStatement,
40
+ }),
41
+ options,
42
+ model,
43
+ operation: 'FindUnique',
44
+ })
45
+
46
+ await writeFileSafely({
47
+ content: generateFindFirstFunction({
48
+ model,
49
+ prismaImportStatement,
50
+ }),
51
+ options,
52
+ model,
53
+ operation: 'FindFirst',
54
+ })
55
+
56
+ await writeFileSafely({
57
+ content: generateFindManyFunction({
58
+ model,
59
+ prismaImportStatement,
60
+ }),
61
+ options,
62
+ model,
63
+ operation: 'FindMany',
64
+ })
65
+
66
+ await writeFileSafely({
67
+ content: generateCreateFunction({
68
+ model,
69
+ prismaImportStatement,
70
+ }),
71
+ options,
72
+ model,
73
+ operation: 'Create',
74
+ })
75
+
76
+ await writeFileSafely({
77
+ content: generateCreateManyFunction({
78
+ model,
79
+ prismaImportStatement,
80
+ }),
81
+ options,
82
+ model,
83
+ operation: 'CreateMany',
84
+ })
85
+
86
+ await writeFileSafely({
87
+ content: generateUpdateFunction({
88
+ model,
89
+ prismaImportStatement,
90
+ }),
91
+ options,
92
+ model,
93
+ operation: 'Update',
94
+ })
95
+
96
+ await writeFileSafely({
97
+ content: generateUpdateManyFunction({
98
+ model,
99
+ prismaImportStatement,
100
+ }),
101
+ options,
102
+ model,
103
+ operation: 'UpdateMany',
104
+ })
105
+
106
+ await writeFileSafely({
107
+ content: generateUpsertFunction({
108
+ model,
109
+ prismaImportStatement,
110
+ }),
111
+ options,
112
+ model,
113
+ operation: 'Upsert',
114
+ })
115
+
116
+ await writeFileSafely({
117
+ content: generateDeleteFunction({
118
+ model,
119
+ prismaImportStatement,
120
+ }),
121
+ options,
122
+ model,
123
+ operation: 'Delete',
124
+ })
125
+
126
+ await writeFileSafely({
127
+ content: generateDeleteManyFunction({
128
+ model,
129
+ prismaImportStatement,
130
+ }),
131
+ options,
132
+ model,
133
+ operation: 'DeleteMany',
134
+ })
135
+
136
+ await writeFileSafely({
137
+ content: generateAggregateFunction({
138
+ model,
139
+ prismaImportStatement,
140
+ }),
141
+ options,
142
+ model,
143
+ operation: 'Aggregate',
144
+ })
145
+
146
+ await writeFileSafely({
147
+ content: generateCountFunction({
148
+ model,
149
+ prismaImportStatement,
150
+ }),
151
+ options,
152
+ model,
153
+ operation: 'Count',
154
+ })
155
+
156
+ await writeFileSafely({
157
+ content: generateGroupByFunction({
158
+ model,
159
+ prismaImportStatement,
160
+ }),
161
+ options,
162
+ model,
163
+ operation: 'GroupBy',
164
+ })
165
+
166
+ await writeFileSafely({
167
+ content: generateRouterFunction({ model }),
168
+ options,
169
+ model,
170
+ operation: 'index',
171
+ })
172
+ })
173
+ },
174
+ })
@@ -0,0 +1,58 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles aggregation 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 generateAggregateFunction = (options: {
11
+ model: DMMF.Model
12
+ prismaImportStatement: string
13
+ }): string => {
14
+ const { model, prismaImportStatement } = options
15
+ const modelName = model.name
16
+ const functionName = `${modelName}Aggregate`
17
+ const argsTypeName = `Prisma.${modelName}AggregateArgs`
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 AggregateRequest extends Request {
26
+ prisma: PrismaClient;
27
+ body: ${argsTypeName};
28
+ outputValidation?: ZodTypeAny;
29
+ omitOutputValidation?: boolean;
30
+ }
31
+
32
+ export type AggregateMiddleware = RequestHandler<ParamsDictionary, any, ${argsTypeName}, Record<string, any>>;
33
+
34
+ export async function ${functionName}(req: AggregateRequest, 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()}.aggregate(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 aggregation request:', error);
54
+ res.status(500).json({ error: error.message });
55
+ next(error);
56
+ }
57
+ }`
58
+ }
@@ -0,0 +1,58 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles count 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 generateCountFunction = (options: {
11
+ model: DMMF.Model
12
+ prismaImportStatement: string
13
+ }): string => {
14
+ const { model, prismaImportStatement } = options
15
+ const modelName = model.name
16
+ const functionName = `${modelName}Count`
17
+ const argsTypeName = `Prisma.${modelName}CountArgs`
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 CountRequest extends Request {
26
+ prisma: PrismaClient;
27
+ body: ${argsTypeName};
28
+ outputValidation?: ZodTypeAny;
29
+ omitOutputValidation?: boolean;
30
+ }
31
+
32
+ export type CountMiddleware = RequestHandler<ParamsDictionary, any, ${argsTypeName}, Record<string, any>>;
33
+
34
+ export async function ${functionName}(req: CountRequest, 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()}.count(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 count request:', error);
54
+ res.status(500).json({ error: error.message });
55
+ next(error);
56
+ }
57
+ }`
58
+ }
@@ -0,0 +1,58 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles creation of 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 generateCreateFunction = (options: {
10
+ model: DMMF.Model
11
+ prismaImportStatement: string
12
+ }): string => {
13
+ const { model, prismaImportStatement } = options
14
+ const modelName = model.name
15
+ const functionName = `${modelName}Create`
16
+ const argsTypeName = `Prisma.${modelName}CreateArgs`
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 CreateRequest extends Request {
25
+ prisma: PrismaClient;
26
+ body: ${argsTypeName};
27
+ outputValidation?: ZodTypeAny;
28
+ omitOutputValidation?: boolean;
29
+ }
30
+
31
+ export type CreateMiddleware = RequestHandler<ParamsDictionary, any, ${argsTypeName}, Record<string, any>>
32
+
33
+ export async function ${functionName}(req: CreateRequest, 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()}.create(req.body);
40
+ if (!req.omitOutputValidation && req.outputValidation) {
41
+ const validationResult = req.outputValidation.safeParse(data);
42
+ if (validationResult.success) {
43
+ res.status(201).json(validationResult.data);
44
+ } else {
45
+ res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
46
+ }
47
+ } else if (!req.omitOutputValidation) {
48
+ throw new Error('Output validation schema must be provided unless explicitly omitted.');
49
+ } else {
50
+ res.status(201).json(data);
51
+ }
52
+ } catch (error) {
53
+ console.error('Error in handling create request:', error);
54
+ res.status(500).json({ error: error.message });
55
+ next(error);
56
+ }
57
+ }`
58
+ }
@@ -0,0 +1,58 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles the creation of 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 generateCreateManyFunction = (options: {
10
+ model: DMMF.Model
11
+ prismaImportStatement: string
12
+ }): string => {
13
+ const { model, prismaImportStatement } = options
14
+ const modelName = model.name
15
+ const functionName = `${modelName}CreateMany`
16
+ const argsTypeName = `Prisma.${modelName}CreateManyArgs`
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 CreateManyRequest extends Request {
25
+ prisma: PrismaClient;
26
+ body: ${argsTypeName};
27
+ outputValidation?: ZodTypeAny;
28
+ omitOutputValidation?: boolean;
29
+ }
30
+
31
+ export type CreateManyMiddleware = RequestHandler<ParamsDictionary, any, ${argsTypeName}, Record<string, any>>
32
+
33
+ export async function ${functionName}(req: CreateManyRequest, 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()}.createMany(req.body);
40
+ if (!req.omitOutputValidation && req.outputValidation) {
41
+ const validationResult = req.outputValidation.safeParse(data);
42
+ if (validationResult.success) {
43
+ res.status(201).json(validationResult.data);
44
+ } else {
45
+ res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
46
+ }
47
+ } else if (!req.omitOutputValidation) {
48
+ throw new Error('Output validation schema must be provided unless explicitly omitted.');
49
+ } else {
50
+ res.status(201).json(data);
51
+ }
52
+ } catch (error) {
53
+ console.error('Error in handling createMany request:', error);
54
+ res.status(500).json({ error: error.message });
55
+ next(error);
56
+ }
57
+ }`
58
+ }
@@ -0,0 +1,60 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles deleting records
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 generateDeleteFunction = (options: {
11
+ model: DMMF.Model
12
+ prismaImportStatement: string
13
+ }): string => {
14
+ const { model, prismaImportStatement } = options
15
+ const modelName = model.name
16
+ const functionName = `${modelName}Delete`
17
+ const argsTypeName = `Prisma.${modelName}DeleteArgs`
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 DeleteRequest extends Request {
26
+ prisma: PrismaClient;
27
+ body: ${argsTypeName};
28
+ outputValidation?: ZodTypeAny;
29
+ omitOutputValidation?: boolean;
30
+ }
31
+
32
+ export type DeleteMiddleware = RequestHandler<ParamsDictionary, any, ${argsTypeName}, Record<string, any>>
33
+
34
+ export async function ${functionName}(req: DeleteRequest, 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()}.delete(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 delete request:', error);
56
+ res.status(500).json({ error: error.message });
57
+ next(error);
58
+ }
59
+ }`
60
+ }
@@ -0,0 +1,58 @@
1
+ import { DMMF } from '@prisma/generator-helper'
2
+
3
+ /**
4
+ * Generates an Express middleware function that handles batch deleting records
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 generateDeleteManyFunction = (options: {
11
+ model: DMMF.Model
12
+ prismaImportStatement: string
13
+ }): string => {
14
+ const { model, prismaImportStatement } = options
15
+ const modelName = model.name
16
+ const functionName = `${modelName}DeleteMany`
17
+ const argsTypeName = `Prisma.${modelName}DeleteManyArgs`
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 DeleteManyRequest extends Request {
26
+ prisma: PrismaClient;
27
+ body: ${argsTypeName};
28
+ outputValidation?: ZodTypeAny;
29
+ omitOutputValidation?: boolean;
30
+ }
31
+
32
+ export type DeleteManyMiddleware = RequestHandler<ParamsDictionary, any, Prisma.${modelName}DeleteManyArgs, Record<string, any>>;
33
+
34
+ export async function ${functionName}(req: DeleteManyRequest, 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()}.deleteMany(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 batch delete request:', error);
54
+ res.status(500).json({ error: error.message });
55
+ next(error);
56
+ }
57
+ }`
58
+ }