forked from node-red/node-red-node-swagger
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathswagger.js
More file actions
260 lines (230 loc) · 8.08 KB
/
Copy pathswagger.js
File metadata and controls
260 lines (230 loc) · 8.08 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/**
* Copyright 2015, 2016 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
//const swaggerUiDistPath = require('swagger-ui-dist').getAbsoluteFSPath();
const DEFAULT_TEMPLATE = {
openapi: "3.0.0",
info: {
title: "My Node-RED API",
version: "1.0.0",
description: "A sample API",
// You can also add 'termsOfService', 'contact', and 'license' information here
},
servers: [
{
url: "http://localhost:1880/",
description: "Local server",
},
],
paths: {},
components: {
schemas: {},
responses: {},
parameters: {},
securitySchemes: {},
},
tags: [],
// Add more properties as needed
};
module.exports = function (RED) {
"use strict";
//console.log("Dev version of this flow");
const path = require("path");
const convToSwaggerPath = (x) => `/{${x.substring(2)}}`;
const trimAll = (ary) => ary.map((x) => x.trim());
const csvStrToArray = (csvStr) => (csvStr ? trimAll(csvStr.split(",")) : []);
const ensureLeadingSlash = (url) => (url.startsWith("/") ? url : "/" + url);
const stripTerminalSlash = (url) =>
url.length > 1 && url.endsWith("/") ? url.slice(0, -1) : url;
const regexColons = /\/:\w*/g;
RED.httpNode.get("/http-api/swagger.json", (req, res) => {
const {
httpNodeRoot,
openapi: { template = {}, parameters: additionalParams = [] } = {},
} = RED.settings;
const resp = { ...DEFAULT_TEMPLATE, ...template };
const { basePath = httpNodeRoot } = resp;
resp.paths = {};
RED.nodes.eachNode((node) => {
const { name, type, method, swaggerDoc, url } = node;
if (type === "http in") {
const swaggerDocNode = RED.nodes.getNode(swaggerDoc);
if (swaggerDocNode) {
const endPoint = ensureLeadingSlash(
url.replace(regexColons, convToSwaggerPath)
);
if (!resp.paths[endPoint]) resp.paths[endPoint] = {};
// request body is permitted in methods GET, HEAD, DELETE but should be avoided https://swagger.io/specification/#operation-object
// editors will show invalid if those methods have an request body -> if not explicit set, do not set it
const avoidRequestBody = ['get', 'head', 'delete']
const {
summary = swaggerDocNode.summary || name || method + " " + endPoint,
description = swaggerDocNode.description || "",
tags = swaggerDocNode.tags || "",
deprecated = swaggerDocNode.deprecated || false,
parameters = swaggerDocNode.parameters || [],
requestBody = swaggerDocNode.requestBody || (avoidRequestBody.includes(method.toLowerCase()) ? undefined : {}),
} = swaggerDocNode;
const aryTags = csvStrToArray(tags);
const operation = {
summary,
description,
tags: aryTags,
deprecated,
parameters: [...parameters, ...additionalParams].map((param) => {
return {
name: param.name,
in: param.in,
required: param.required,
schema: {
type: param.type,
},
description: param.description,
};
}),
requestBody: requestBody,
responses: {},
};
if (
swaggerDocNode &&
typeof swaggerDocNode.responses === "object" &&
swaggerDocNode.responses !== null
) {
Object.keys(swaggerDocNode.responses).forEach((status) => {
const responseDetails = swaggerDocNode.responses[status];
operation.responses[status] = {
description: responseDetails.description || "No description",
content: {},
};
if (responseDetails.schema) {
operation.responses[status].content["application/json"] = {
schema: responseDetails.schema,
};
}
});
} else {
console.error(
"swaggerDocNode.responses is not an object or is null:",
swaggerDocNode.responses
);
}
resp.paths[endPoint][method.toLowerCase()] = operation;
} else {
console.error(
"No Swagger Documentation node found for HTTP In node:",
node.id
);
}
}
});
// Final cleanup to remove empty sections
cleanupOpenAPISpec(resp);
res.json(resp);
});
function cleanupOpenAPISpec(spec) {
// Clean up components
if (spec.components) {
["schemas", "responses", "parameters", "securitySchemes"].forEach(
(key) => {
if (
spec.components[key] &&
Object.keys(spec.components[key]).length === 0
) {
delete spec.components[key];
}
}
);
// If all components are empty, remove the components object itself
if (Object.keys(spec.components).length === 0) {
delete spec.components;
}
}
// Clean up empty tags array
if (Array.isArray(spec.tags) && spec.tags.length === 0) {
delete spec.tags;
}
}
function SwaggerDoc(n) {
RED.nodes.createNode(this, n);
this.summary = n.summary;
this.description = n.description;
this.tags = n.tags;
this.parameters = n.parameters;
this.responses = n.responses;
this.requestBody = n.requestBody; // Ensure requestBody is captured
this.deprecated = n.deprecated;
}
RED.nodes.registerType("swagger-doc", SwaggerDoc);
// Serve the main Swagger UI HTML file
RED.httpAdmin.get("/swagger-ui/swagger-ui.html", (req, res) => {
// Correct the path to point directly to the 'swagger-ui.html' file
const filename = path.join(__dirname, "swagger-ui/swagger-ui.html");
sendFile(res, filename);
});
// Serve i18next localization files
RED.httpAdmin.get("/swagger-ui/i18next.min.js", (req, res) => {
const filename = path.join(
__dirname,
"..",
"node_modules",
"i18next",
"i18next.min.js"
);
sendFile(res, filename);
});
// Serve Swagger UI assets like CSS and JS from swagger-ui-dist
RED.httpAdmin.get(
"/swagger-ui/*",
(req, res, next) => {
// Extract the actual file name from the request params
let filename = req.params[0];
// If the filename is 'swagger-ui.html', redirect to the correct handler
if (filename === "swagger-ui.html") {
return next();
}
// Serve the file from swagger-ui-dist
try {
const basePath = require("swagger-ui-dist").getAbsoluteFSPath();
const filePath = path.join(basePath, filename);
sendFile(res, filePath);
} catch (err) {
console.error(err);
res.status(404).send("File not found");
}
},
(req, res) => {
// Fallback handler for 'swagger-ui.html', in case the above handler is triggered
// due to the way Express handles wildcard routes
const filename = path.join(__dirname, "swagger", "swagger-ui.html");
sendFile(res, filename);
}
);
// Serve any other localization files
RED.httpAdmin.get("/swagger-ui/nls/*", (req, res) => {
const filename = path.join(__dirname, "locales", req.params[0]);
sendFile(res, filename);
});
// Generic function to send files
function sendFile(res, filePath) {
// Implement the logic to send the file
// For example, using Express' res.sendFile:
res.sendFile(filePath, (err) => {
if (err) {
console.error("Error sending file:", err);
res.status(err.status || 500).send("Error sending file.");
}
});
}
};