# inversify-hapijs-utils

> Some utilities for the development of hapijs rest applications with Inversify

Latest version **3.2.0** (published 2020-06-17) · MIT license · 0 weekly downloads

## Install

```sh
npm install inversify-hapijs-utils
pnpm add inversify-hapijs-utils
yarn add inversify-hapijs-utils
bun add inversify-hapijs-utils
```

## Health

**Score 40/100 (D)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned.

## Facts

| | |
|---|---|
| Version | 3.2.0 |
| Published | 2020-06-17 |
| First published | 2017-11-20 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 2 |
| Unpacked size | 27.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Andrew Wheeler |
| Maintainers | andrewwh |
| Keywords | InversifyJS, hapijs, dependency, injection |

## Links

- npm: https://www.npmjs.com/package/inversify-hapijs-utils
- Repository: https://github.com/ericsonmichaelj/inversify-hapijs-utils
- Homepage: https://github.com/ericsonmichaelj/inversify-hapijs-utils#readme
- npm.io page: https://npm.io/package/inversify-hapijs-utils

## Dependencies (2)

- [inversify](https://npm.io/package/inversify.md) ^5.0.1
- [@hapi/hapi](https://npm.io/package/@hapi/hapi.md) >=18.4.1

## Recent versions

- 3.2.0 (latest) — 2020-06-17
- 1.2.0 (lts) — 2020-06-19
- 0.0.7 (legacy) — 2020-06-19
- 0.0.6 — 2020-05-30
- 1.1.0 — 2020-05-29
- 2.1.1 — 2020-05-29
- 3.1.1 — 2020-05-29
- 2.1.0 — 2020-05-27
- 3.1.0 — 2020-05-26
- 3.0.1 — 2020-05-23
- 2.0.2 — 2020-05-23
- 1.0.3 — 2020-05-23
- 0.0.5 — 2020-05-23
- 3.0.0 — 2020-05-22
- 2.0.1 — 2020-05-22
- … 8 more at https://npm.io/package/inversify-hapijs-utils/versions

## README

# inversify-hapijs-utils

[![npm version](https://badge.fury.io/js/inversify-hapijs-utils.svg)](https://badge.fury.io/js/inversify-hapijs-utils) [![npm downloads](https://img.shields.io/npm/dm/inversify-hapijs-utils.svg)](https://npmcharts.com/compare/inversify-hapijs-utils?minimal=true) [![Build Status](https://travis-ci.org/ericsonmichaelj/inversify-hapijs-utils.svg?branch=master)](https://travis-ci.org/ericsonmichaelj/inversify-hapijs-utils)
[![Code Coverage](https://codecov.io/gh/ericsonmichaelj/inversify-hapijs-utils/branch/master/graph/badge.svg)](https://codecov.io/gh/ericsonmichaelj/inversify-hapijs-utils) [![Known Vulnerabilities](https://snyk.io/test/github/ericsonmichaelj/inversify-hapijs-utils/badge.svg)](https://snyk.io/test/github/ericsonmichaelj/inversify-hapijs-utils)



## Version Support

The version of inversify-hapijs-utils depends on which version of hapi you plan on using. Below lists the corresponding version of hapi used for each inversify-hapijs-utils version:

| inversify-hapijs-utils | @hapi/hapi | hapi
| ------ | ------ | ------ | 
|  [0.0.x](https://www.npmjs.com/package/inversify-hapijs-utils/v/0.0.5) | n/a | ^16.6.2
| [1.x.x](https://www.npmjs.com/package/inversify-hapijs-utils/v/1.0.3)  | n/a | ^17.8.5
| [2.x.x](https://www.npmjs.com/package/inversify-hapijs-utils/v/2.0.2) | ^18.4.1 | n/a
| [^3.2.x](https://www.npmjs.com/package/inversify-hapijs-utils/) | >=18.4.1 | n/a

## Installation
You can install `inversify-hapijs-utils` using npm:

```
$ npm install inversify inversify-hapijs-utils reflect-metadata --save
```


The `inversify-hapijs-utils` type definitions are included in the npm module and require TypeScript 2.0.
Please refer to the [InversifyJS documentation](https://github.com/inversify/InversifyJS#installation) to learn more about the installation process.

This version requires node 12 or higher.

## The Basics

### Step 1: Decorate your controllers
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'.

```ts
import { Request } from 'hapijs';
import { Controller, Get, interfaces } from 'inversify-hapijs-utils';
import { injectable, inject } from 'inversify';

@Controller('/foo')
@injectable()
export class FooController implements interfaces.Controller {
        
    @Get('/')
    private index(req: Request): string {
        return 'foo'
    }
}
```

> 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.

### Step 2: Configure container and server
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-hapijs-utils is empty and solely for convenience, so feel free to implement your own if you want.

```ts
import { Container } from 'inversify';
import { interfaces, InversifyHapiServer, TYPE } from 'inversify-hapijs-utils';

// 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, {port: 8080});


server
    .build()
    .start();
```

## InversifyHapiServer
A wrapper for a hapijs Application.


### `.build()`
Attaches all registered controllers and middleware to the hapijs application. Returns the application instance.

```ts
// ...
let server = new InversifyHapiServer(container, {port: 8080});

server.setConfig(async(app) => {
    await app.register({
        plugin: require("hapi-pino")
    });
});

const init = async() => {
    const serverInstance = await server.build();
    serverInstance.start();
}

init();
```

## Decorators

### `@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`, `@Delete`, and `@Options`. For anything more obscure, use `@Method` (Or make a PR :smile:).

## Middleware
Middleware can be either an instance of `RequestHandler` or an InversifyJS service identifier. 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. You must return a value. If it is a side-effect, than you can return `null`;

```ts
// ...
import * as Boom from "boom";

const loggingHandler = (req: Request) => {
  console.log(req);
  return null;
};

const securityHandler = (req: Request) => {
  // Return a Boom (or any Error) if you want processing to stop
  if (!req.headers['token']) {
      return Boom.unauthorized('No session id in request header');
  }

  return null;
};

@Controller('/foo', loggingHandler, securityHandler)
@injectable()
export class FooController {
    
    @Get('/', loggingHandler)
    private index(req: Request): string {
        return 'foo'
    }
}
```

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.

```ts
// ...
import { TYPES } from 'types';
// ...
const loggingHandler = (req: Request) => {
  console.log(req);
  return null;
};
container.bind<RequestHandler>(TYPES.LoggingMiddleware).toConstantValue(loggingHandler);
// ...
@Controller('/foo', TYPES.LoggingMiddleware)
@injectable()
export class FooController implements interfaces.Controller {
   
    @Get('/', TYPES.LoggingMiddleware)
    private index(req: Request): string {
        return 'foo'
    }
}
```

## Error Handling
HapiJs supports Boom objects.

```ts
// ...
const TYPES = {
  Controller: Symbol.for("Controller"),
  FooService: "FooService",
  loggingMiddleware: Symbol.for("loggingMiddleware")
};
// ...
import { Request } from "hapi";
import { injectable, inject } from "inversify";
import * as Boom from "boom";

@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);
    }
}
```

## Support and Contributing

If you have any questions or issues using inversify-hapijs-utils please post your issues [here](https://github.com/ericsonmichaelj/inversify-hapijs-utils/issues):

If you want to contribute, create a PR in the [repository](https://github.com/ericsonmichaelj/inversify-hapijs-utils)

---
_Source: https://npm.io/package/inversify-hapijs-utils · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
