Skip to content

Instantly share code, notes, and snippets.

@nfroidure
Created June 5, 2017 09:44
Show Gist options
  • Save nfroidure/647189bdeffef33bced3a3b6d924640e to your computer and use it in GitHub Desktop.
Save nfroidure/647189bdeffef33bced3a3b6d924640e to your computer and use it in GitHub Desktop.
`swagger-http-router` with manual DI
import { getInstance, initializer } from 'knifecycle';
import uuid from 'uuid';
import { initDelayService } from 'common-services';
import {
initRouter,
initHTTP,
initHTTPTransaction
} from 'swagger-http-router';
import swaggerDefinition from './my-swagger.json';
import * as HANDLERS from './handlers';
import initDB from './services/db';
try {
// STEP 1: Create common services
const services = {
log: console.log.bind(console),
time: Date.now.bind(Date),
uniqueId: uuid.v4,
ENV: process.env,
};
const delayProvider = await initDelayService(services);
services.delay = delayProvider.service;
const dbProvider = await initDb(services);
services.db = dbProvider.service;
// STEP 2: Instantiate handlers
await Promise.all(
Object.keys(HANDLERS)
.map((handlerName) => {
return HANDLERS[handlerName](services)
.then((handler) => {
services[handlerName] = handler;
});
})
);
services.HANDLERS = HANDLERS;
// STEP 3: Register your API definition
services.API = swaggerDefinition;
// STEP 4: Start the router
const httpRouterProvider = await initHTTPRouter(services);
services.router = httpRouterProvider.service;
const httpServerProvider = await initHTTPServer(services);
services.httpServer = httpServerProvider.service;
log('info', `On air 🚀🌕`);
function shutdown() {
await httpServerProvider.dispose();
await httpRouterProvider.dispose();
await dbProvider.dispose();
}
process.on('SIGTERM', shutdown);
} catch(err) {
console.error('💀 - Cannot launch the process:', err.stack);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment