-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
52 lines (42 loc) · 1.77 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
'use strict'
var fs = require('fs');
var serveStatic = require('koa-static');
var favIconHtml = '<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />' +
'<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />'
var setup = function(swaggerDoc, explorer, options, customCss, customfavIcon) {
options = options || {};
var explorerString = explorer ? '' : '.swagger-ui .topbar .download-url-wrapper { display: none }';
customCss = explorerString + ' ' + customCss || explorerString;
customfavIcon = customfavIcon || false;
var html = fs.readFileSync(__dirname + '/indexTemplate.html');
try {
fs.unlinkSync(__dirname + '/index.html');
} catch (e) {
}
var htmlWithSwaggerReplaced = html.toString().replace('<% swaggerDoc %>', JSON.stringify(swaggerDoc));
var favIconString = customfavIcon ? '<link rel="icon" href="' + customfavIcon + '" />' : favIconHtml;
var indexHTML = htmlWithSwaggerReplaced.replace('<% customOptions %>', stringify(options))
var htmlWithCustomCss = indexHTML.replace('<% customCss %>', customCss);
var htmlWithFavIcon = htmlWithCustomCss.replace('<% favIconString %>', favIconString);
return async function(ctx, next) { ctx.body = htmlWithFavIcon };
};
var serve = serveStatic(__dirname + '/static');
var stringify = function(obj, prop) {
var placeholder = '____FUNCTIONPLACEHOLDER____';
var fns = [];
var json = JSON.stringify(obj, function(key, value) {
if (typeof value === 'function') {
fns.push(value);
return placeholder;
}
return value;
}, 2);
json = json.replace(new RegExp('"' + placeholder + '"', 'g'), function(_) {
return fns.shift();
});
return json + ';';
};
module.exports = {
setup: setup,
serve: serve
};