/**
* ### Swagger Helper Library
*
* This module is a wrapper around Swagger-Tools library
*
* @module Library/Swagger
*/
"use strict";
const fs = require("fs");
const path = require("path");
const {
get
} = require("lodash/fp");
const BPromise = require("bluebird");
const swaggerTools = require("swagger-tools");
const yaml = require("js-yaml");
const utils = require(path.resolve(__dirname, "./utils"));
const logAndResolve = utils.logAndResolve;
const getModulePath = utils.getModulePath;
const config = require(getModulePath("config")).swagger;
const entities = require(getModulePath("api/controllers/entities"));
const actions = require(getModulePath("api/controllers/actions"));
// Wrapper around promisifying fs.readFile
exports.readFileAsync = (fileName) => new BPromise(
function(resolve, reject) {
try {
fs.readFile(
fileName, "utf8", (err, contents) => ((err) ? reject(err) : resolve(contents)));
} catch (e) {
reject(e);
}
});
// This wrapper is used to make swagger-tools initializeMiddleware behave like
// a Promise based function
exports.wrapper = (fa, fb) => (arg) => new BPromise(
function(resolve, reject) {
try {
fa(arg, (b) => resolve(fb(b)));
} catch (e) {
reject(e);
}
});
// This function is used to setup our middleware which is based on the swagger
// one, which is generated from our spec by swagger-tools
exports.configuration = (swaggerMW) => [
swaggerMW.swaggerMetadata(),
swaggerMW.swaggerValidator({
validateResponse: get("validateResponse", config) || true
}),
swaggerMW.swaggerRouter({
useStubs: get("useStubs", config) || false,
controllers: {
actions_list: actions.list,
actions_refresh: actions.refresh,
actions_create: actions.create,
actions_getById: actions.getById,
actions_update: actions.update,
actions_remove: actions.remove,
entities_list: entities.list,
entities_refresh: entities.refresh,
entities_create: entities.create,
entities_getById: entities.getById,
entities_update: entities.update,
entities_remove: entities.remove
}
}),
swaggerMW.swaggerUi({
apiDocs: get("apiDocs", config) || "/api-spec",
swaggerUI: get("swaggerUI", config) || "/docs"
})
];
exports.initMiddleware = () => BPromise
.try(logAndResolve("info", "Adding Swagger middleware"))
.then(() => exports.readFileAsync(getModulePath("api/swagger.yaml"), "utf8"))
.then(yaml.safeLoad)
.then(exports.wrapper(
swaggerTools.initializeMiddleware,
exports.configuration));