-
Notifications
You must be signed in to change notification settings - Fork 81
/
index.js
92 lines (72 loc) · 2.3 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
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
var assert = require('assert'),
express = require('express'),
thing = require('core-util-is'),
path = require('path'),
caller = require('caller'),
expressroutes = require('./expressroutes'),
url = require('url'),
routes = require('swaggerize-routes'),
yaml = require('js-yaml'),
fs = require('fs');
function swaggerize(options) {
var app;
assert.ok(thing.isObject(options), 'Expected options to be an object.');
assert.ok(options.api, 'Expected an api definition.');
if (thing.isString(options.api)) {
options.api = loadApi(options.api);
}
assert.ok(thing.isObject(options.api), 'Api definition must resolve to an object.');
options.basedir = path.dirname(caller());
options.routes = routes(options);
app = express();
app.once('mount', mount(app, options));
return app;
}
/**
* Onmount handler.
* @param options
* @returns {onmount}
*/
function mount(app, options) {
return function onmount(parent) {
var settings;
parent._router.stack.pop();
//If a mountpath was provided, override basePath in api.
options.api.basePath = app.mountpath !== '/' ? app.mountpath : options.api.basePath;
Object.keys(settings = {
"x-powered-by": false,
"trust proxy": false,
"jsonp callback name": null,
"json replacer": null,
"json spaces": 0,
"case sensitive routing": false,
"strict routing": false,
"views": null,
"view cache": false,
"view engine": false
}).forEach(function (name) {
parent.set(name, settings[name]);
});
parent.mountpath = options.api.basePath;
Object.defineProperty(parent, 'swagger', {
value: {
api: options.api,
routes: options.routes
}
});
expressroutes(parent._router, options);
};
}
/**
* Loads the api from a path, with support for yaml..
* @param apiPath
* @returns {Object}
*/
function loadApi(apiPath) {
if (apiPath.indexOf('.yaml') === apiPath.length - 5 || apiPath.indexOf('.yml') === apiPath.length - 4) {
return yaml.load(fs.readFileSync(apiPath));
}
return require(apiPath);
}
module.exports = swaggerize;