prisma-generator-express 1.0.5 → 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/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # [1.1.0](https://github.com/multipliedtwice/prisma-generator-express/compare/v1.0.0...v1.1.0) (2024-05-15)
2
+
3
+
4
+ ### Features
5
+
6
+ * **generator:** add MIT License and README file for Prisma Generator Express ([6c99565](https://github.com/multipliedtwice/prisma-generator-express/commit/6c995652c53946e0f3f303f0495fcfe4e7b96e48))
7
+ * **generator:** update package.json description to provide a more specific description of the Prisma generator for Express CRUD API ([7b99050](https://github.com/multipliedtwice/prisma-generator-express/commit/7b99050d2089490082b6c6b7f5174f8572172779))
8
+
9
+ # 1.0.0 (2024-05-15)
10
+
11
+
12
+ ### Bug Fixes
13
+
14
+ * **generator:** update minimum required Node.js version to 20.0 in engines field ([1b4e7b2](https://github.com/multipliedtwice/prisma-generator-express/commit/1b4e7b2a8e29cc8a9710cc6393ada81b01631de3))
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.5",
4
+ "version": "1.1.0",
5
5
  "main": "dist/generator.js",
6
6
  "license": "MIT",
7
7
  "bin": {
@@ -15,8 +15,7 @@
15
15
  "dev": "npx tsc -w",
16
16
  "build": "npx tsc",
17
17
  "prepack": "yarn build",
18
- "test": "jest",
19
- "prepublishOnly": "node copy.js "
18
+ "test": "jest"
20
19
  },
21
20
  "dependencies": {
22
21
  "@prisma/client": "5.14.0",
@@ -37,13 +36,12 @@
37
36
  "prisma": "5.14.0",
38
37
  "semantic-release": "^23.1.1",
39
38
  "ts-jest": "29.1.2",
40
- "shx": "^0.3.4",
41
39
  "typescript": "5.4.5"
42
40
  },
43
41
  "homepage": "https://github.com/multipliedtwice/prisma-generator-express/blob/master/README.md",
44
42
  "repository": {
45
43
  "type": "git",
46
- "url": "git+https://github.com/multipliedtwice/prisma-generator-express.git"
44
+ "url": "https://github.com/multipliedtwice/prisma-generator-express"
47
45
  },
48
46
  "author": "multipliedtwice",
49
47
  "keywords": [
@@ -52,12 +50,6 @@
52
50
  "crud",
53
51
  "generator"
54
52
  ],
55
- "files": [
56
- "dist/**/*",
57
- "src/**/*",
58
- "../../README.md",
59
- "../../LICENSE"
60
- ],
61
53
  "release": {
62
54
  "branches": [
63
55
  "master"
@@ -85,4 +77,4 @@
85
77
  ]
86
78
  ]
87
79
  }
88
- }
80
+ }
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.genEnum = void 0;
4
- const genEnum = ({ name, values }) => {
5
- const enumValues = values.map(({ name }) => `${name}="${name}"`).join(',\n');
6
- return `enum ${name} { \n${enumValues}\n }`;
7
- };
8
- exports.genEnum = genEnum;
9
- //# sourceMappingURL=genEnum.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"genEnum.js","sourceRoot":"","sources":["../../src/helpers/genEnum.ts"],"names":[],"mappings":";;;AAEO,MAAM,OAAO,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,EAAsB,EAAE,EAAE;IAC9D,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,GAAG,IAAI,KAAK,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IAE5E,OAAO,QAAQ,IAAI,QAAQ,UAAU,MAAM,CAAA;AAC7C,CAAC,CAAA;AAJY,QAAA,OAAO,WAInB"}
@@ -1,49 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateFindUniqueFunction = void 0;
4
- const generateFindUniqueFunction = (options) => {
5
- const { model, prismaImportStatement } = options;
6
- const modelName = model.name;
7
- const functionName = `${modelName}FindUnique`;
8
- const queryTypeName = `Prisma.${modelName}FindUniqueArgs`;
9
- return `
10
- ${prismaImportStatement}
11
- import { Request, Response, NextFunction } from 'express';
12
- import { ParsedQs } from 'qs';
13
- import { ZodTypeAny } from 'zod';
14
-
15
- interface PrismaRequest extends Request {
16
- prisma: PrismaClient;
17
- query: ${queryTypeName} & ParsedQs;
18
- outputValidation?: ZodTypeAny;
19
- omitOutputValidation?: boolean;
20
- }
21
-
22
- export async function ${functionName}(req: PrismaRequest, res: Response, next: NextFunction) {
23
- try {
24
- if (!req.outputValidation && !req.omitOutputValidation) {
25
- throw new Error('Output validation schema or omission flag must be provided.');
26
- }
27
-
28
- const data = await req.prisma.${modelName.toLowerCase()}.findUnique(req.query as ${queryTypeName});
29
- if (!req.omitOutputValidation && req.outputValidation) {
30
- const validationResult = req.outputValidation.safeParse(data);
31
- if (validationResult.success) {
32
- res.status(200).json(validationResult.data);
33
- } else {
34
- res.status(400).json({ error: 'Invalid data format', details: validationResult.error });
35
- }
36
- } else if (!req.omitOutputValidation) {
37
- throw new Error('Output validation schema must be provided unless explicitly omitted. Attach omitOutputValidation = true to request to suppress this error.');
38
- } else {
39
- res.status(200).json(data);
40
- }
41
- } catch (error) {
42
- console.error('Error in handling request:', error);
43
- res.status(500).json({ error: error.message });
44
- next(error);
45
- }
46
- }`;
47
- };
48
- exports.generateFindUniqueFunction = generateFindUniqueFunction;
49
- //# sourceMappingURL=generateFindUnique%20copy.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generateFindUnique copy.js","sourceRoot":"","sources":["../../src/helpers/generateFindUnique copy.ts"],"names":[],"mappings":";;;AAQO,MAAM,0BAA0B,GAAG,CAAC,OAG1C,EAAU,EAAE;IACX,MAAM,EAAE,KAAK,EAAE,qBAAqB,EAAE,GAAG,OAAO,CAAA;IAChD,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAA;IAC5B,MAAM,YAAY,GAAG,GAAG,SAAS,YAAY,CAAA;IAC7C,MAAM,aAAa,GAAG,UAAU,SAAS,gBAAgB,CAAA;IAEzD,OAAO;EACP,qBAAqB;;;;;;;WAOZ,aAAa;;;;;wBAKA,YAAY;;;;;;oCAMA,SAAS,CAAC,WAAW,EAAE,4BAA4B,aAAa;;;;;;;;;;;;;;;;;;EAkBlG,CAAA;AACF,CAAC,CAAA;AA/CY,QAAA,0BAA0B,8BA+CtC"}
@@ -1,2 +0,0 @@
1
- "use strict";
2
- //# sourceMappingURL=generatePrismaImport.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generatePrismaImport.js","sourceRoot":"","sources":["../../src/helpers/generatePrismaImport.ts"],"names":[],"mappings":""}
@@ -1,14 +0,0 @@
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
@@ -1 +0,0 @@
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"}
package/src/bin.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import './generator'
package/src/constants.ts DELETED
@@ -1 +0,0 @@
1
- export const GENERATOR_NAME = 'prisma-generator-express'
package/src/generator.ts DELETED
@@ -1,174 +0,0 @@
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
- })
@@ -1,58 +0,0 @@
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
- }
@@ -1,58 +0,0 @@
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
- }
@@ -1,58 +0,0 @@
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
- }
@@ -1,58 +0,0 @@
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
- }
@@ -1,60 +0,0 @@
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
- }