prisma-swagger-autogen 1.0.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/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2026 QUIKK Software GmbH / Joyce Marvin Rafflenbeul
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,264 @@
1
+ # Prisma Swagger Autogen
2
+
3
+ Generate a **fully typed OpenAPI 3 specification directly from your Prisma models** and use it seamlessly with **`swagger-autogen`**.
4
+
5
+ This package allows you to treat **Prisma as the single source of truth** for your API data structures and automatically expose those structures as **correct Swagger schemas**, without manually duplicating DTOs or schema definitions.
6
+
7
+ ---
8
+
9
+ ## ✨ What This Tool Is For
10
+
11
+ The main goal of this package is:
12
+
13
+ > **To automatically generate correct Swagger/OpenAPI schemas based on your Prisma models, so that Swagger, Swagger UI, and generated API clients all share the same types.**
14
+
15
+ Instead of:
16
+ - manually writing OpenAPI schemas
17
+ - duplicating DTOs
18
+ - maintaining separate validation and documentation layers
19
+
20
+ you can rely on **Prisma’s type system** and generate everything from there.
21
+
22
+ ---
23
+
24
+ ## 🔁 How It Fits Into Your Tooling
25
+
26
+ This tool is designed to work **together with `swagger-autogen`**, not replace it.
27
+
28
+ ### The workflow looks like this:
29
+
30
+ 1. **Prisma models** define your domain
31
+ 2. This package:
32
+ - reads Prisma DMMF
33
+ - generates OpenAPI schemas (`components.schemas`)
34
+ - builds a ready-to-use `swagger.config.js`
35
+ 3. **`swagger-autogen`**:
36
+ - scans your controllers
37
+ - uses the generated config
38
+ - produces a complete `openapi.json`
39
+ 4. Optional:
40
+ - generate a TypeScript client
41
+ - generate SDKs
42
+ - use Swagger UI
43
+
44
+ ✔ One source of truth
45
+ ✔ No duplicated schemas
46
+ ✔ No mismatched DTOs
47
+
48
+ ---
49
+
50
+ ## 🚀 Why This Matters
51
+
52
+ Without this approach, teams often end up with:
53
+
54
+ - Prisma models
55
+ - Request/Response DTOs
56
+ - Swagger schemas
57
+ - Client-side models
58
+
59
+ …all slightly different.
60
+
61
+ This tool ensures that:
62
+
63
+ - **Prisma → Swagger is automatic**
64
+ - **Swagger schemas are structurally correct**
65
+ - **Swagger-generated TypeScript clients contain real data shapes**
66
+ - **Request bodies and responses are usable out of the box**
67
+
68
+ ---
69
+
70
+ ## ❌ What This Tool Does *Not* Do
71
+
72
+ - It does **not** replace `swagger-autogen`
73
+ - It does **not** scan controllers itself
74
+ - It does **not** generate routes
75
+
76
+ Instead, it **prepares the Swagger configuration** so that `swagger-autogen` can do its job properly.
77
+
78
+ ---
79
+
80
+ ## 📦 Installation
81
+
82
+ ```bash
83
+ npm install -D prisma-swagger-autogen
84
+ ```
85
+
86
+ ---
87
+
88
+ ## 🛠 Usage
89
+
90
+ 1. Generate swagger.config.js from Prisma
91
+
92
+ ```
93
+ npx prisma-swagger-autogen
94
+ ```
95
+
96
+ This will generate a swagger.config.js file in your project root.
97
+
98
+ The file already contains:
99
+
100
+ - components.schemas derived from Prisma
101
+ - security schemes
102
+ - server configuration
103
+ - controller file paths
104
+
105
+ 2. Run swagger-autogen
106
+
107
+ ```
108
+ node swagger.config.js
109
+ ```
110
+
111
+ This generates:
112
+
113
+ `src/web/api/openapi.json`
114
+
115
+ 3. (Optional) Generate a TypeScript API client
116
+
117
+ ```
118
+ npx swagger-typescript-api \
119
+ -p src/web/api/openapi.json \
120
+ -o src/web/api/client \
121
+ -n api.ts
122
+ ```
123
+
124
+
125
+ The resulting TypeScript types now match your Prisma models:
126
+
127
+ ```typescript
128
+ export interface GetUserResponse {
129
+ userId: string;
130
+ name: string;
131
+ birthday?: string;
132
+ }
133
+ ```
134
+
135
+
136
+ No OpenAPI schema metadata. No `type?: string`.
137
+
138
+ ---
139
+
140
+ ## 🧠 Design Philosophy
141
+
142
+ ### Prisma as the Source of Truth
143
+
144
+ Prisma already defines:
145
+
146
+ - field types
147
+ - nullability
148
+ - relations
149
+ - lists
150
+ - enums
151
+
152
+ This tool leverages that information to generate correct OpenAPI schemas, instead of redefining them manually.
153
+
154
+ ---
155
+
156
+ ### Swagger-Autogen Friendly
157
+
158
+ The generated `swagger.config.js` is intentionally designed to:
159
+
160
+ - be plain JavaScript
161
+ - be executable by Node.js
162
+ - be consumed directly by swagger-autogen
163
+
164
+ No runtime magic, no custom Swagger parser.
165
+
166
+ ---
167
+
168
+ ## ⚙️ Default Configuration
169
+
170
+ ```typescript
171
+ {
172
+ controllersGlob: "./src/web/api/controllers/**/*.ts",
173
+ openapiOut: "./src/web/api/openapi.json",
174
+ serviceTitle: "My Service",
175
+ serverUrl: "http://localhost:3000",
176
+ omitFieldsInWriteDtos: ["id", "createdAt", "updatedAt"]
177
+ }
178
+ ```
179
+
180
+ ---
181
+
182
+ ## 🧩 Requirements
183
+
184
+ - Node.js ≥ 18
185
+ - Prisma Client (@prisma/client)
186
+ - swagger-autogen
187
+
188
+ Prisma schema already generated (prisma generate)
189
+
190
+ ---
191
+
192
+ ## ⚠️ Common Pitfalls
193
+ 1. Missing request bodies in Swagger UI
194
+
195
+ Controllers still need proper swagger-autogen annotations:
196
+
197
+ ```typescript
198
+ /* #swagger.requestBody = {
199
+ required: true,
200
+ content: {
201
+ "application/json": {
202
+ schema: { $ref: "#/components/schemas/PostUserRequest" }
203
+ }
204
+ }
205
+ } */
206
+ ```
207
+
208
+
209
+ This tool provides the schemas — the controller annotations wire them up.
210
+
211
+ 2. Primitive types leaking as OpenAPI schema objects
212
+
213
+ If your generated TypeScript client contains types like this:
214
+
215
+ ```typescript
216
+ name?: {
217
+ type?: string;
218
+ format?: string;
219
+ };
220
+ ```
221
+
222
+
223
+ then your OpenAPI schemas are being interpreted as schema definitions instead of data shapes.
224
+
225
+ This usually happens when:
226
+
227
+ - OpenAPI schemas expose type, properties, items, etc. as part of the object
228
+ - TypeScript generators mirror those schema internals instead of resolving them
229
+
230
+ ✔ This tool explicitly generates schemas in a way that swagger-autogen + swagger-typescript-api interpret as real DTOs, resulting in:
231
+
232
+ `name?: string;`
233
+
234
+ If you still see `type?: string` fields in your client:
235
+
236
+ - ensure the OpenAPI spec was generated using the swagger.config.js from this tool
237
+ - ensure you regenerated the client after regenerating openapi.json
238
+
239
+ ---
240
+
241
+ ## 📄 License
242
+
243
+ MIT
244
+
245
+ ---
246
+
247
+ ## 🤝 Contributing
248
+
249
+ Contributions are welcome, especially for:
250
+
251
+ - Prisma edge cases
252
+ - Advanced relation handling
253
+ - Custom schema naming strategies
254
+
255
+ ---
256
+
257
+ ## ⭐ Summary
258
+
259
+ Prisma Swagger Autogen enables you to:
260
+
261
+ - define your API models once (in Prisma)
262
+ - automatically expose them in Swagger
263
+ - generate clean, usable API clients
264
+ - keep documentation, backend, and frontend in sync
@@ -0,0 +1,334 @@
1
+ // src/index.ts
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { globSync } from "glob";
5
+ import { execSync } from "child_process";
6
+ var CONFIG = {
7
+ projectRoot: process.cwd(),
8
+ controllersGlob: "./src/web/api/controllers/**/*.ts",
9
+ outFile: "./swagger.config.js",
10
+ openapiOut: "./src/web/api/openapi.json",
11
+ serviceTitle: "Prescription Service",
12
+ serverUrl: "http://localhost:3008",
13
+ securitySchemeName: "keycloakOAuth",
14
+ oauth: {
15
+ tokenUrl: "http://auth.localhost/realms/haemo/protocol/openid-connect/token",
16
+ refreshUrl: "http://auth.localhost/realms/haemo/protocol/openid-connect/refresh",
17
+ scopes: { openid: "openid scope" }
18
+ },
19
+ omitFieldsInWriteDtos: /* @__PURE__ */ new Set(["id", "createdAt", "updatedAt", "v"])
20
+ };
21
+ function ensurePosix(p) {
22
+ return p.split(path.sep).join(path.posix.sep);
23
+ }
24
+ function pluralize(name) {
25
+ if (name.endsWith("s")) return `${name}es`;
26
+ return `${name}s`;
27
+ }
28
+ function scalarToSchema(scalar) {
29
+ switch (scalar) {
30
+ case "String":
31
+ return { type: "string" };
32
+ case "Boolean":
33
+ return { type: "boolean" };
34
+ case "Int":
35
+ return { type: "integer" };
36
+ case "BigInt":
37
+ return { type: "integer", format: "int64" };
38
+ case "Float":
39
+ return { type: "number" };
40
+ case "Decimal":
41
+ return { type: "number" };
42
+ case "DateTime":
43
+ return { type: "string", format: "date-time" };
44
+ case "Json":
45
+ return { type: "object" };
46
+ case "Bytes":
47
+ return { type: "string", format: "byte" };
48
+ default:
49
+ return { type: "string" };
50
+ }
51
+ }
52
+ function fieldSchema(field, getRefName) {
53
+ if (field.kind === "scalar") {
54
+ const base = scalarToSchema(field.type);
55
+ if (field.isList) return { type: "array", items: base };
56
+ return base;
57
+ }
58
+ if (field.kind === "enum") {
59
+ const base = { $ref: `#/components/schemas/${field.type}` };
60
+ if (field.isList) return { type: "array", items: base };
61
+ return base;
62
+ }
63
+ if (field.kind === "object") {
64
+ const ref = { $ref: `#/components/schemas/${getRefName(String(field.type))}` };
65
+ if (field.isList) return { type: "array", items: ref };
66
+ return ref;
67
+ }
68
+ return { type: "object" };
69
+ }
70
+ function modelToGetSchema(model, getRefName) {
71
+ const properties = {};
72
+ const required = [];
73
+ for (const f of model.fields) {
74
+ properties[f.name] = fieldSchema(f, getRefName);
75
+ if (f.isRequired) required.push(f.name);
76
+ }
77
+ const schema = { type: "object", properties };
78
+ if (required.length) schema.required = required;
79
+ return schema;
80
+ }
81
+ function stripWriteFields(model, getSchema, omit) {
82
+ const schema = JSON.parse(JSON.stringify(getSchema));
83
+ if (!schema.properties) return schema;
84
+ const relationFieldNames = new Set(model.fields.filter((f) => f.kind === "object").map((f) => f.name));
85
+ for (const key of Object.keys(schema.properties)) {
86
+ if (omit.has(key) || relationFieldNames.has(key)) delete schema.properties[key];
87
+ }
88
+ if (Array.isArray(schema.required)) {
89
+ schema.required = schema.required.filter((k) => !omit.has(k) && !relationFieldNames.has(k));
90
+ if (schema.required.length === 0) delete schema.required;
91
+ }
92
+ return schema;
93
+ }
94
+ function makeAllOptional(schema) {
95
+ const s = JSON.parse(JSON.stringify(schema));
96
+ delete s.required;
97
+ return s;
98
+ }
99
+ function listResponseSchema(itemRef) {
100
+ return {
101
+ type: "object",
102
+ properties: {
103
+ count: { type: "number", example: 3 },
104
+ hasPreviousPage: { type: "boolean", example: false },
105
+ hasNextPage: { type: "boolean", example: true },
106
+ pageNumber: { type: "number", example: 1 },
107
+ pageSize: { type: "number", example: 10 },
108
+ totalPages: { type: "number", example: 1 },
109
+ items: { type: "array", items: { $ref: itemRef } }
110
+ },
111
+ required: ["count", "hasPreviousPage", "hasNextPage", "pageNumber", "pageSize", "totalPages", "items"]
112
+ };
113
+ }
114
+ function exampleForScalarType(type, format) {
115
+ if (type === "string" && format === "date-time") return (/* @__PURE__ */ new Date(0)).toISOString();
116
+ switch (type) {
117
+ case "string":
118
+ return "string";
119
+ case "integer":
120
+ return 0;
121
+ case "number":
122
+ return 0;
123
+ case "boolean":
124
+ return true;
125
+ case "object":
126
+ return {};
127
+ default:
128
+ return null;
129
+ }
130
+ }
131
+ function buildExampleFromSchema(schema, components, depth = 0) {
132
+ if (depth > 2) return void 0;
133
+ if (schema.$ref) {
134
+ const name = String(schema.$ref).split("/").pop() || "";
135
+ const target = components[name];
136
+ if (!target) return void 0;
137
+ return buildExampleFromSchema(target, components, depth + 1);
138
+ }
139
+ if (Array.isArray(schema.allOf) && schema.allOf.length) {
140
+ const merged = {};
141
+ for (const part of schema.allOf) {
142
+ const ex = buildExampleFromSchema(part, components, depth + 1);
143
+ if (ex && typeof ex === "object" && !Array.isArray(ex)) Object.assign(merged, ex);
144
+ }
145
+ return Object.keys(merged).length ? merged : void 0;
146
+ }
147
+ if (schema.type === "array" && schema.items) {
148
+ const item = buildExampleFromSchema(schema.items, components, depth + 1);
149
+ return item === void 0 ? [] : [item];
150
+ }
151
+ if (schema.type === "object" && schema.properties) {
152
+ const obj = {};
153
+ for (const [k, v] of Object.entries(schema.properties)) {
154
+ const ex = buildExampleFromSchema(v, components, depth + 1);
155
+ if (ex !== void 0) obj[k] = ex;
156
+ }
157
+ return obj;
158
+ }
159
+ if (Array.isArray(schema.enum) && schema.enum.length) return schema.enum[0];
160
+ if (typeof schema.type === "string") return exampleForScalarType(schema.type, schema.format);
161
+ return void 0;
162
+ }
163
+ function attachExample(schema, components) {
164
+ const s = JSON.parse(JSON.stringify(schema));
165
+ if (s.example === void 0) {
166
+ const ex = buildExampleFromSchema(s, components);
167
+ if (ex !== void 0) s.example = ex;
168
+ }
169
+ return s;
170
+ }
171
+ async function loadDmmfFromProject() {
172
+ const schemaPath = path.resolve(process.cwd(), "prisma/schema.prisma");
173
+ if (!fs.existsSync(schemaPath)) {
174
+ throw new Error(`Prisma schema not found at: ${schemaPath}`);
175
+ }
176
+ const cmd = `npx prisma generate --schema "${schemaPath}" --print`;
177
+ const stdout = execSync(cmd, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
178
+ const firstBrace = stdout.indexOf("{");
179
+ const lastBrace = stdout.lastIndexOf("}");
180
+ if (firstBrace === -1 || lastBrace === -1) {
181
+ throw new Error(`Failed to parse Prisma DMMF from: ${cmd}`);
182
+ }
183
+ const jsonText = stdout.slice(firstBrace, lastBrace + 1);
184
+ const parsed = JSON.parse(jsonText);
185
+ const dmmf = parsed?.dmmf ?? parsed;
186
+ if (!dmmf?.datamodel?.models) {
187
+ throw new Error(`Prisma DMMF not found in prisma output. Got keys: ${Object.keys(parsed || {})}`);
188
+ }
189
+ return dmmf;
190
+ }
191
+ function buildSchemasFromDmmf(dmmf) {
192
+ const schemas = {};
193
+ const getRefName = (modelName) => `Get${modelName}Response`;
194
+ for (const e of dmmf.datamodel.enums) {
195
+ schemas[e.name] = { type: "string", enum: e.values.map((v) => v.name) };
196
+ }
197
+ for (const model of dmmf.datamodel.models) {
198
+ const getName = `Get${model.name}Response`;
199
+ const postName = `Post${model.name}Request`;
200
+ const putName = `Put${model.name}Request`;
201
+ const listName = `List${pluralize(model.name)}Response`;
202
+ const getSchema = modelToGetSchema(model, getRefName);
203
+ const postSchema = stripWriteFields(model, getSchema, CONFIG.omitFieldsInWriteDtos);
204
+ const putSchema = makeAllOptional(postSchema);
205
+ schemas[getName] = getSchema;
206
+ schemas[postName] = postSchema;
207
+ schemas[putName] = putSchema;
208
+ schemas[listName] = listResponseSchema(`#/components/schemas/${getName}`);
209
+ }
210
+ schemas["ExceptionResponse"] = {
211
+ type: "object",
212
+ properties: {
213
+ detail: { type: "string" },
214
+ errors: { type: "array", items: { type: "string" } },
215
+ status: { type: "number" },
216
+ title: { type: "string" },
217
+ type: { type: "string" }
218
+ },
219
+ required: ["status", "title", "type"]
220
+ };
221
+ schemas["BadRequestResponse"] = {
222
+ allOf: [{ $ref: "#/components/schemas/ExceptionResponse" }],
223
+ example: {
224
+ status: 400,
225
+ title: "The request was invalid",
226
+ type: "https://tools.ietf.org/html/rfc7231#section-6.5.1"
227
+ }
228
+ };
229
+ schemas["NotFoundResponse"] = {
230
+ allOf: [{ $ref: "#/components/schemas/ExceptionResponse" }],
231
+ example: {
232
+ status: 404,
233
+ title: "The specified resource was not found",
234
+ type: "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.4"
235
+ }
236
+ };
237
+ schemas["InternalErrorResponse"] = {
238
+ allOf: [{ $ref: "#/components/schemas/ExceptionResponse" }],
239
+ example: {
240
+ status: 500,
241
+ title: "An error occurred while processing your request",
242
+ type: "https://tools.ietf.org/html/rfc7231#section-6.6.1"
243
+ }
244
+ };
245
+ for (const name of Object.keys(schemas)) {
246
+ if (name.startsWith("Post") && name.endsWith("Request")) schemas[name] = attachExample(schemas[name], schemas);
247
+ if (name.startsWith("Put") && name.endsWith("Request")) schemas[name] = attachExample(schemas[name], schemas);
248
+ }
249
+ return schemas;
250
+ }
251
+ function generateSwaggerConfigJs(schemas) {
252
+ const routes = globSync(CONFIG.controllersGlob, { nodir: true }).map((p) => ensurePosix(p));
253
+ const docs = {
254
+ info: { title: CONFIG.serviceTitle },
255
+ servers: [{ url: CONFIG.serverUrl }],
256
+ components: {
257
+ schemas,
258
+ securitySchemes: {
259
+ [CONFIG.securitySchemeName]: {
260
+ type: "oauth2",
261
+ description: "This API uses OAuth2 with the password flow.",
262
+ flows: {
263
+ password: {
264
+ tokenUrl: CONFIG.oauth.tokenUrl,
265
+ refreshUrl: CONFIG.oauth.refreshUrl,
266
+ scopes: CONFIG.oauth.scopes
267
+ }
268
+ }
269
+ }
270
+ }
271
+ },
272
+ security: [{ [CONFIG.securitySchemeName]: ["openid"] }]
273
+ };
274
+ const fileContent = `const swaggerAutogen = require('swagger-autogen')();
275
+ const fs = require('fs');
276
+ const path = require('node:path');
277
+
278
+ function isPlainObject(v){return v!==null && typeof v==='object' && !Array.isArray(v);}
279
+
280
+ function normalizeSchema(schema){
281
+ if(!isPlainObject(schema)) return schema;
282
+ if(schema.$ref) return schema;
283
+
284
+ if(isPlainObject(schema.type) && typeof schema.type.example === 'string') schema.type = schema.type.example;
285
+ if(isPlainObject(schema.format) && typeof schema.format.example === 'string') schema.format = schema.format.example;
286
+ if(isPlainObject(schema.required) && Array.isArray(schema.required.example)) schema.required = schema.required.example;
287
+ if(isPlainObject(schema.enum) && Array.isArray(schema.enum.example)) schema.enum = schema.enum.example;
288
+
289
+ if(Array.isArray(schema.allOf)) schema.allOf = schema.allOf.map(normalizeSchema);
290
+ if(isPlainObject(schema.items)) schema.items = normalizeSchema(schema.items);
291
+ if(isPlainObject(schema.additionalProperties)) schema.additionalProperties = normalizeSchema(schema.additionalProperties);
292
+
293
+ if(isPlainObject(schema.properties)){
294
+ for(const k of Object.keys(schema.properties)){
295
+ schema.properties[k] = normalizeSchema(schema.properties[k]);
296
+ }
297
+ }
298
+
299
+ return schema;
300
+ }
301
+
302
+ function fixOpenApiFile(openapiPath){
303
+ const abs = path.resolve(process.cwd(), openapiPath);
304
+ if(!fs.existsSync(abs)) return;
305
+ const doc = JSON.parse(fs.readFileSync(abs,'utf8'));
306
+
307
+ if(doc && doc.components && isPlainObject(doc.components.schemas)){
308
+ for(const name of Object.keys(doc.components.schemas)){
309
+ doc.components.schemas[name] = normalizeSchema(doc.components.schemas[name]);
310
+ }
311
+ }
312
+
313
+ fs.writeFileSync(abs, JSON.stringify(doc,null,2),'utf8');
314
+ }
315
+
316
+ const docs = ${JSON.stringify(docs, null, 2)};
317
+ const routes = ${JSON.stringify(routes, null, 2)};
318
+
319
+ swaggerAutogen('${ensurePosix(CONFIG.openapiOut)}', routes, docs)
320
+ .then(() => fixOpenApiFile('${ensurePosix(CONFIG.openapiOut)}'))
321
+ .catch((e) => { console.error(e); process.exitCode = 1; });
322
+ `;
323
+ const outPath = path.resolve(CONFIG.projectRoot, CONFIG.outFile);
324
+ fs.writeFileSync(outPath, fileContent, "utf8");
325
+ }
326
+ async function run(_args) {
327
+ const dmmf = await loadDmmfFromProject();
328
+ const schemas = buildSchemasFromDmmf(dmmf);
329
+ generateSwaggerConfigJs(schemas);
330
+ }
331
+
332
+ export {
333
+ run
334
+ };