Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
inversify-hapi-decorators
Advanced tools
Some utilities for the development of hapijs rest applications with Inversify
A fork of
andrewwh/inversify-hapijs-utils
Some utilities for the development of hapijs application with Inversify. Based on the inversify-restify.utils. If you're starting writing restful api's then I suggest you use Restify (and the inversify-restify-utils). If you want to use hapi (or you have to) then this project can help you in the same way that inversify-restify.utils does.
Note: this project is still a work in progress and does not have any test coverage.
You can install inversify-hapi-decorators
using npm:
$ npm install inversify inversify-hapi-decorators reflect-metadata --save
The inversify-hapi-decorators
type definitions are included in the npm module and require TypeScript 2.0.
Please refer to the InversifyJS documentation to learn more about the installation process.
To use a class as a "controller" for your hapijs app, simply add the @Controller
decorator to the class. Similarly, decorate methods of the class to serve as request handlers.
The following example will declare a controller that responds to `GET /foo'.
import { Request } from 'hapijs';
import { Controller, Get, interfaces } from 'inversify-hapi-decorators';
import { injectable, inject } from 'inversify';
@Controller('/foo')
@injectable()
export class FooController implements interfaces.Controller {
constructor( @inject('FooService') private fooService: FooService ) {}
@Get('/')
private index(req: Request): string {
return this.fooService.get(req.query.id);
}
}
Note: The controller should not use the hapijs reply method to control output, but rather it should return the result directly. Any errors should return a Boom error.
Configure the inversify container in your composition root as usual.
Then, pass the container to the InversifyHapiServer constructor. This will allow it to register all controllers and their dependencies from your container and attach them to the hapi app. Then just call server.build() to prepare your app.
In order for the InversifyHapiServer to find your controllers, you must bind them to the TYPE.Controller
service identifier and tag the binding with the controller's name.
The Controller
interface exported by inversify-hapi-decorators is empty and solely for convenience, so feel free to implement your own if you want.
import { Container } from 'inversify';
import { interfaces, InversifyHapiServer, TYPE } from 'inversify-hapi-decorators';
// set up container
let container = new Container();
// note that you *must* bind your controllers to Controller
container.bind<interfaces.Controller>(TYPE.Controller).to(FooController).whenTargetNamed('FooController');
container.bind<FooService>('FooService').to(FooService);
// create server
let server = new InversifyHapiServer(container);
server
.build()
.start(
(err) => {
if (err) {
console.log(err);
}
}
);
hapijs ServerOptions can be provided as a second parameter to the InversifyHapiServer constructor:
let server = new InversifyHapiServer(container, { name: "my-server" });
hapijs ServerOptions can be extended with defaultRoot
where one can define a default path that will be prepended to all your controllers:
let server = new InversifyHapiServer(container, { name: "my-server", defaultRoot: "/v1" });
A wrapper for a hapijs Application.
.setConfig(configFn)
Optional - exposes the hapijs application object for convenient loading of server-level middleware.
import * as morgan from 'morgan';
// ...
let server = new InversifyHapiServer(container);
server.setConfig((app) => {
app.connection({port: 8080});
});
.build()
Attaches all registered controllers and middleware to the hapijs application. Returns the application instance.
// ...
let server = new InversifyHapiServer(container);
server
.setConfig(configFn)
.build()
.start(err => {});
@Controller(path, [middleware, ...])
Registers the decorated class as a controller with a root path, and optionally registers any global middleware for this controller.
@Method(method, path, [middleware, ...])
Registers the decorated controller method as a request handler for a particular path and method, where the method name is a valid hapijs routing method.
@SHORTCUT(path, [middleware, ...])
Shortcut decorators which are simply wrappers for @Method
. Right now these include @Get
, @Post
, @Put
, @Patch
, @Head
, @Delete
, and @Options
. For anything more obscure, use @Method
(Or make a PR :smile:).
Middleware can be either an instance of RequestHandler
or an InversifyJS service identifier. This is attached as a route 'pre' method. To stop processing you will need to return a Boom error or a javascript Error.
The simplest way to use middleware is to define a RequestHandler
instance and pass that handler as decorator parameter.
// ...
const loggingHandler = (req: Request, reply: ReplyNoContinue) => {
console.log(req);
return reply.continue();
};
const securityHandler = (req: Request, reply: ReplyNoContinue) => {
// Return a Boom (or any Error) if you want processing to stop
if (!req.headers['token']) {
return reply(Boom.unauthorized('No esi session id in request header'));
}
return reply.continue();
};
@Controller('/foo', loggingHandler, securityHandler)
@injectable()
export class FooController {
constructor( @inject('FooService') private fooService: FooService ) {}
@Get('/', loggingHandler)
private index(req: Request): string {
return this.fooService.get(req.query.id);
}
}
But if you wish to take full advantage of InversifyJS you can bind the same handler to your IOC container and pass the handler's service identifier to decorators.
// ...
import { TYPES } from 'types';
// ...
const loggingHandler = (req: Request, reply: ReplyNoContinue) => {
console.log(req);
};
container.bind<RequestHandler>(TYPES.LoggingMiddleware).toConstantValue(loggingHandler);
// ...
@Controller('/foo', TYPES.LoggingMiddleware)
@injectable()
export class FooController implements interfaces.Controller {
constructor( @inject('FooService') private fooService: FooService ) {}
@Get('/', TYPES.LoggingMiddleware)
private index(req: Request): string {
return this.fooService.get(req.query.id);
}
}
HapiJs supports Boom objects.
@Controller('/foo', TYPES.LoggingMiddleware)
@injectable()
export class FooController implements interfaces.Controller {
constructor( @inject('FooService') private fooService: FooService ) {}
@Get('/{id}')
private index(req: Request): string {
if (!req.params.id) {
return Boom.badRequest('id is required');
}
return this.fooService.get(req.query.id);
}
}
FAQs
Some utilities for the development of hapijs rest applications with Inversify
The npm package inversify-hapi-decorators receives a total of 1 weekly downloads. As such, inversify-hapi-decorators popularity was classified as not popular.
We found that inversify-hapi-decorators demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.