42 lines
1.4 KiB
TypeScript
42 lines
1.4 KiB
TypeScript
|
import swagger from 'swagger-ui-express';
|
||
|
import jsonRefParser, {JSONSchema} from '@apidevtools/json-schema-ref-parser';
|
||
|
|
||
|
|
||
|
// modifies the normal swagger-ui-express package
|
||
|
// usage: app.use('/api', api.serve(), api.setup());
|
||
|
// the paths property can be split using allOf
|
||
|
// further route documentation can be included in the x-doc property
|
||
|
|
||
|
export default class api {
|
||
|
static serve () {
|
||
|
return swagger.serve;
|
||
|
}
|
||
|
|
||
|
static setup () {
|
||
|
let apiDoc: JSONSchema = {};
|
||
|
jsonRefParser.bundle('api/api.yaml', (err, doc) => { // parse yaml
|
||
|
if(err) throw err;
|
||
|
apiDoc = doc;
|
||
|
apiDoc.paths = apiDoc.paths.allOf.reduce((s, e) => Object.assign(s, e)); // bundle routes
|
||
|
apiDoc = this.resolveXDoc(apiDoc);
|
||
|
swagger.setup(apiDoc);
|
||
|
});
|
||
|
return swagger.setup(apiDoc, {customCssUrl: '/static/styles/swagger.css'})
|
||
|
}
|
||
|
|
||
|
private static resolveXDoc (doc) { // resolve x-doc properties recursively
|
||
|
Object.keys(doc).forEach(key => {
|
||
|
if (doc[key] !== null && doc[key].hasOwnProperty('x-doc')) {
|
||
|
doc[key].description += this.addHtml(doc[key]['x-doc']);
|
||
|
}
|
||
|
else if (typeof doc[key] === 'object' && doc[key] !== null) { // go deeper into recursion
|
||
|
doc[key] = this.resolveXDoc(doc[key]);
|
||
|
}
|
||
|
});
|
||
|
return doc;
|
||
|
}
|
||
|
|
||
|
private static addHtml (text) { // add docs HTML
|
||
|
return '<details class="docs"><summary>docs</summary>' + text + '</details>';
|
||
|
}
|
||
|
}
|