import * as _ from 'lodash' import * as path from 'path' import * as fs from 'fs' import * as chalk from 'chalk' import * as express from 'express' import * as isPromise from 'is-promise' export { UserError } from "./errors" import { expand } from "./expander" import Server from "./server" import { CLIError } from "./errors" export function loadSpec(dir) { if (!fs.existsSync(path.join(dir, 'api.json'))) throw new CLIError(`Could not access ${chalk.yellow('./api.json')} from ${chalk.yellow(dir)}`) let spec = JSON.parse(fs.readFileSync(path.join(dir, 'api.json'))) spec.dir = path.resolve(dir, spec.dir || '.') return expand(spec) } export function createServer(spec) { const server = new Server() const controllers = require(path.resolve(spec.dir, spec.main ? spec.main : 'controller')) _.forEach(spec.endpoints, (endpointSpec, route) => { const controllerName = endpointSpec.controller server.endpoint(route, controllerName) }) const endpointControllers = _.values(spec.endpoints).map(_.property('controller')) async function finalize(app) { for (const controllerName of endpointControllers) if (!server.hasController(controllerName)) console.log(chalk.red(`Controller ${chalk.yellow(controllerName)} not found at initial startup.`)) return server } _.forEach(_.omit(controllers, 'init'), (callback, name) => { server.controller(name, (params) => callback(app, params)) }) if (controllers.init) { const res = controllers.init(spec) if (isPromise(res)) return res .then(finalize) .catch(e => console.log(e)) else finalize(res) } else { return finalize({}) } }