How to use inversify-express-utils - 10 common examples

To help you get started, we’ve selected a few inversify-express-utils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DefinitelyTyped / DefinitelyTyped / inversify-express-utils / inversify-express-utils-tests.ts View on Github external
/// 

import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method, TYPE } from "inversify-express-utils";
import * as express from "express";
import { Kernel } from "inversify";

let kernel = new Kernel();

module server {

    let server = new InversifyExpressServer(kernel);

    server
        .setConfig((app: express.Application) => {
            app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
                console.log("hello world");
                next();
            });
        })
        .setErrorConfig((app: express.Application) => {
            app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
                console.error(err.stack);
                res.status(500).send("Something broke!");
            });
        })
        .build()
        .listen(3000, "localhost");
github robertmain / jukebox / src / index.ts View on Github external
import { TYPES } from './Types';
import config from './config';
import AudioSource from './api/services/media_providers/AudioSource';
import AudioFactory from './api/services/media_providers/AudioFactory';
import DiskSource from './api/services/media_providers/disk/DiskSource';
import DiskFactory from './api/services/media_providers/disk/DiskFactory';

let container = new Container();

container.bind(TYPE.Controller).to(Song).whenTargetNamed('Song');
container.bind(TYPES.AudioSource).to(DiskSource);
container.bind(TYPES.AudioFactory).to(DiskFactory);
container.bind(TYPES.Config).toConstantValue(config);

// create server
let server = new InversifyExpressServer(container);

server
    .build()
    .listen(config.webServer.port, config.webServer.bind_address, () => {
        console.log('Now listening on ' + config.webServer.bind_address + ':' + config.webServer.port);
    });
github robertmain / jukebox / src / index.ts View on Github external
import "reflect-metadata";
import { Container } from 'inversify';
import { interfaces as IExpressUtils, InversifyExpressServer, TYPE } from 'inversify-express-utils';

import Song from './api/controllers/Song';
import { TYPES } from './Types';
import config from './config';
import AudioSource from './api/services/media_providers/AudioSource';
import AudioFactory from './api/services/media_providers/AudioFactory';
import DiskSource from './api/services/media_providers/disk/DiskSource';
import DiskFactory from './api/services/media_providers/disk/DiskFactory';

let container = new Container();

container.bind(TYPE.Controller).to(Song).whenTargetNamed('Song');
container.bind(TYPES.AudioSource).to(DiskSource);
container.bind(TYPES.AudioFactory).to(DiskFactory);
container.bind(TYPES.Config).toConstantValue(config);

// create server
let server = new InversifyExpressServer(container);

server
    .build()
    .listen(config.webServer.port, config.webServer.bind_address, () => {
        console.log('Now listening on ' + config.webServer.bind_address + ':' + config.webServer.port);
    });
github julianosam / ts-express-ddd-seed / src / presentation / rest / movie / movie.controller.ts View on Github external
import { RentMovieCommand } from '../../../application/movie/commands/rent-movie-command';

@injectable()
@controller('/api')
export class MovieController {

    constructor(
        @inject('MovieStoreApplicationService') private _movieStoreAppSvc: MovieStoreApplicationService
    ) { }

    // @httpGet('/movies/query')
    // searchMovies(request: any, response: Response) {

    // }

    @httpPost('/movies/commands/register')
    registerMovie(request: any, response: Response) {

        const movieRegCmd = new RegisterMovieCommand();
        movieRegCmd.requestDate = new Date();
        movieRegCmd.storeAdminId = request.headers['customer-id'];
        movieRegCmd.sectionName = request.body.sectionName;
        movieRegCmd.movie = request.body.movie;

        return this._movieStoreAppSvc.registerMovie(movieRegCmd).then((movie) => {
            response.send(movie);
        }).catch((err: Error) => {
            logger.error(err.message);
            logger.error(err.stack);

            response.status(HTTP_CODES.INTERNAL_SERVER_ERROR).send(err.message);
        });
github secret-tech / backend-ico-dashboard / src / app.ts View on Github external
if (
    !req.header('Content-Type') ||
    (req.header('Content-Type') !== 'application/json' && !req.header('Content-Type').includes('application/x-www-form-urlencoded'))
  ) {
    return res.status(406).json({
      error: 'Unsupported "Content-Type"'
    });
  }

  return next();
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

let server = new InversifyExpressServer(container, null, null, app);
server.setErrorConfig((app) => {
  // 404 handler
  app.use((req: Request, res: Response, next: NextFunction) => {
    res.status(404).send({
      statusCode: 404,
      error: 'Route is not found'
    });
  });

  // exceptions handler
  app.use((err: Error, req: Request, res: Response, next: NextFunction) => handle(err, req, res, next));
});

export default server.build();
github stelltec / public-tech-demos / nodejs-madrid-meetup / demo3 / src / infrastructure / bootstrapping / bootstrap.ts View on Github external
export async function bootstrap(
    container: Container,
    appPort: number,
    dbHost: string,
    dbName: string,
    ...modules: ContainerModule[]
) {

    if (container.isBound(TYPES.App) === false) {

        const dbClient = await getDatabaseClient(dbHost, dbName);
        container.bind(TYPES.DbClient).toConstantValue(dbClient);
        container.load(...modules);

        // Configure express server
        const server = new InversifyExpressServer(container);

        server.setConfig((app) => {

            // Disable default cache
            app.set("etag", false);

            // Configure requests body parsing
            app.use(bodyParser.urlencoded({ extended: true }));
            app.use(bodyParser.json());

            // Adds some decurity defaults
            app.use(helmet());

            // Log all requets that hit the server
            app.use(reqMiddleware);
github ERS-HCL / nxplorerjs-microservice-starter / server / common / server.ts View on Github external
constructor() {
    let root: string;

    // Setup application root
    root =
      process.env.NODE_ENV === 'development'
        ? path.normalize(__dirname + '/../..')
        : path.normalize('.');
    const container = IOCContainer.getInstance().getContainer();
    this.server = new InversifyExpressServer(container, undefined, {
      rootPath: '/api/v1'
    });
    this.server.setConfig(app => {
      // Add security configuration
      secureApp(app);

      app.use((req, res, next) => {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
        res.header(
          'Access-Control-Allow-Headers',
          'Origin, X-Requested-With, Content-Type, Accept'
        );
        next();
      });
github stelltec / public-tech-demos / nodejs-madrid-meetup / demo3 / src / ui / rest_api / controllers / secure_controller.ts View on Github external
import { injectable } from "inversify";
import { Controller, Get } from "inversify-express-utils";
import { authMiddleware } from "../middleware/auth_middleware";

// This is an example of a controller protected by the auth middleware

@injectable()
@Controller("/api/secure", authMiddleware({ role: "admin" }))
export class SecureController {

    @Get("/")
    public async get() {
        return Promise.resolve(["This", "data", "is", "secure!"]);
    }

}
github secret-tech / backend-ico-dashboard / src / ioc.container.ts View on Github external
container.bind('InvestValidation').toConstantValue(
  (req: any, res: any, next: any) => validation.invest(req, res, next)
);
container.bind('OnlyJumioIp').toConstantValue(
  (req: any, res: any, next: any) => validation.onlyJumioIp(req, res, next)
);
container.bind('ResendVerificationValidation').toConstantValue(
  (req: any, res: any, next: any) => validation.resendVerification(req, res, next)
);
container.bind('OnlyAcceptApplicationJson').toConstantValue(
  (req: any, res: any, next: any) => validation.onlyAcceptApplicationJson(req, res, next)
);

// controllers
container.bind(TYPE.Controller).to(UserController).whenTargetNamed('UserController');
container.bind(TYPE.Controller).to(DashboardController).whenTargetNamed('DashboardController');
container.bind(TYPE.Controller).to(KycController).whenTargetNamed('KycController');
container.bind(TYPE.Controller).to(GatewayController).whenTargetNamed('GatewayController');

export { container };
github julianosam / ts-express-ddd-seed / src / ioc-container.ts View on Github external
import { CustomerRepository } from './domain/customer-repository';
import { TypeORMCustomerRepository } from './infrastructure/db/typeorm/typeorm-customer-repository';
import { CustomerApplicationService } from './application/customer/customer-application-service';
import { MovieStoreApplicationService } from './application/movie/movie-store-application-service';
import { MovieController } from './presentation/rest/movie.controller';
import { CustomerController } from './presentation/rest/customer-controller';

const container = new Container();

// Customer
container.bind(TYPE.Controller).to(CustomerController).inSingletonScope().whenTargetNamed('CustomerController');
container.bind('CustomerApplicationService').to(CustomerApplicationService).inSingletonScope();
container.bind('CustomerRepository').to(TypeORMCustomerRepository).inSingletonScope();

// Movies
container.bind(TYPE.Controller).to(MovieController).inSingletonScope().whenTargetNamed('MovieController');
container.bind('MovieStoreApplicationService').to(MovieStoreApplicationService).inSingletonScope();
container.bind('MovieRepository').to(TypeORMMovieRepository).inSingletonScope();

// Database
container.bind('TypeORMConnectionService').to(TypeORMConnectionService).inSingletonScope();

export {
  container
};