-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswaggerConfig.js
80 lines (71 loc) · 1.99 KB
/
swaggerConfig.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const swaggerJsdoc = require("swagger-jsdoc");
const yaml = require("yaml");
const fs = require("fs");
/**
* Generate Swagger responses with custom MIME types and content
* @param {Object} responseMap - An object mapping HTTP status codes to response details
* @returns {Object} - Swagger-compliant responses object
*/
function generateSwaggerResponses(responseMap) {
const responses = {};
for (const [statusCode, { mimeType, example }] of Object.entries(responseMap)) {
responses[statusCode] = {
content: {
[mimeType]: {
schema: {
type: typeof example === "string" ? "string" : "object", // Infer type if not explicitly set
example, // Use the given example directly
},
},
},
};
}
return responses;
}
const swaggerDefinition = {
openapi: "3.0.0",
info: {
title: "AJV to Swagger API",
version: "1.0.0",
description: "An API documentation generated from AJV schemas",
},
paths: {
"/register": {
post: {
summary: "Register a new user",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
properties: {
name: { type: "string" },
email: { type: "string", format: "email" },
age: { type: "integer", minimum: 18 },
},
required: ["name", "email"],
},
},
},
},
responses: generateSwaggerResponses({
200: {
mimeType: "application/json",
example: { status: "ok", id: 123 },
}
}),
},
},
},
};
const options = {
swaggerDefinition,
apis: ["./routes/*.js"],
};
const swaggerSpec = swaggerJsdoc(options);
// Convert JSON spec to YAML
const swaggerYaml = yaml.stringify(swaggerSpec);
// Write to a file
fs.writeFileSync("swagger.yaml", swaggerYaml, "utf8");
module.exports = swaggerSpec;