This repository has been archived by the owner on Jul 26, 2022. It is now read-only.
forked from RemyJeancolas/restify-swagger-jsdoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (67 loc) · 2.64 KB
/
index.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
var restify = require('restify');
var swaggerJSDoc = require('swagger-jsdoc');
var path = require('path');
var fs = require('fs');
var mime = require('mime-types');
var createSwaggerPage = (options) => {
if (!options.server) {
throw new Error('options.server is required');
} else if (!options.title) {
throw new Error('options.title is required');
} else if (!options.version) {
throw new Error('options.version is required');
} else if (!options.path) {
throw new Error('options.path is required');
}
var swaggerUiPath = path.dirname(require.resolve('swagger-ui'));
var swaggerSpec = swaggerJSDoc({
swaggerDefinition: {
info: {
title: options.title,
version: options.version,
description: options.description
},
},
apis: options.apis || []
});
// Prepend route prefix if needed
if (options.routePrefix && swaggerSpec.hasOwnProperty('paths')) {
for (var prop in swaggerSpec.paths) {
swaggerSpec.paths['/' + options.routePrefix + prop] = swaggerSpec.paths[prop];
delete(swaggerSpec.paths[prop]);
}
}
var publicPath = options.path.replace(/\/+$/, '');
options.server.get(`${publicPath}/swagger.json`, (req, res, next) => {
res.setHeader('Content-type', 'application/json');
res.send(swaggerSpec);
return next();
});
options.server.get(new RegExp(publicPath + '\/?$'), (req, res, next) => {
res.header('Location', `${publicPath}/index.html`);
res.send(302);
return next();
});
options.server.get(new RegExp(publicPath + '\/(.*)$'), (req, res, next) => {
fs.readFile(path.resolve(swaggerUiPath, req.params[0]), (err, content) => {
if (err) {
return next(new restify.errors.NotFoundError(`File ${req.params[0]} does not exist`));
}
if (req.params[0] === 'index.html') {
var host = (options.host) ? options.host : req.headers.host;
var swaggerJsonFileUrl = `${req.isSecure() ? 'https' : 'http'}://${host}${publicPath}/swagger.json`;
content = content.toString().replace('url = "http://petstore.swagger.io/v2/swagger.json"', `url ="${swaggerJsonFileUrl}"`);
}
var contentType = mime.lookup(req.params[0]);
if (contentType !== false) {
res.setHeader('Content-Type', contentType);
}
res.write(content);
res.end();
return next();
});
});
};
module.exports = {
createSwaggerPage: createSwaggerPage
};