Source: lib/swagger.js

/**
 * ### 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 retrieve swagger-ui compiled asset. It can either
// be in this project node modules, or as a separate module (if this project is
// itself used as a node module)
exports.getSwaggerUiPath = function() {
    const localDependencyPath = path.resolve(__dirname, "../../node_modules/swagger-ui/dist/");
    if (fs.existsSync(localDependencyPath)) {
        return localDependencyPath;
    }
    return path.resolve(__dirname, "../../../swagger-ui/dist/");
};

// 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_listActions: actions.list,
            actions_refreshActions: actions.refresh,
            actions_createAction: actions.create,
            actions_getActionById: actions.getById,
            actions_updateAction: actions.update,
            actions_removeAction: actions.remove,
            actions_performAction: actions.performAction,
            entities_listEntities: entities.list,
            entities_refreshEntities: entities.refresh,
            entities_createEntity: entities.create,
            entities_getEntityById: entities.getById,
            entities_updateEntity: entities.update,
            entities_removeEntity: entities.remove
        }
    }),
    swaggerMW.swaggerUi({
        apiDocs: get("apiDocs", config) || "/api-spec",
        swaggerUI: get("swaggerUI", config) || "/docs",
        swaggerUiDir: exports.getSwaggerUiPath()
    })
];

exports.initMiddleware = () => BPromise
    .try(() => logAndResolve("info", "Adding Swagger middleware", null))
    .then(() => exports.readFileAsync(getModulePath("api/swagger.yaml"), "utf8"))
    .then(yaml.safeLoad)
    .then(exports.wrapper(
        swaggerTools.initializeMiddleware,
        exports.configuration))
    .then(logAndResolve("info", "You can interact with this Semverse by using its API."))
    .then(logAndResolve("info", "API Description is available at: http://localhost:9100/docs?url=http://localhost:9100/api-spec"));