Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'inversify-express-utils' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
///
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");
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);
});
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);
});
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);
});
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();
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);
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();
});
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!"]);
}
}
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 };
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
};