Skip to content

Commit

Permalink
feat(express-middleware): add an extension point for express middleware
Browse files Browse the repository at this point in the history
Add @loopback/express-middleware as a new package
  • Loading branch information
raymondfeng committed Aug 2, 2019
1 parent 0471315 commit 3a9de17
Show file tree
Hide file tree
Showing 19 changed files with 1,455 additions and 0 deletions.
1 change: 1 addition & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ packages/cli/* @raymondfeng @bajtos
packages/context/* @bajtos @raymondfeng
packages/core/* @bajtos @raymondfeng
packages/eslint-config/* @raymondfeng
packages/express-middleware/* @raymondfeng
packages/metadata/* @raymondfeng
packages/openapi-spec-builder/* @bajtos @raymondfeng
packages/openapi-v3/* @bajtos @jannyHou
Expand Down
1 change: 1 addition & 0 deletions docs/site/MONOREPO.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ The [loopback-next](https://github.com/strongloop/loopback-next) repository uses
| [example-soap-calculator](https://github.com/strongloop/loopback-next/tree/master/examples/soap-calculator) | @loopback/example-soap-calculator | A tutorial demonstrating integration with a SOAP webservice |
| [example-todo-list](https://github.com/strongloop/loopback-next/tree/master/examples/todo-list) | @loopback/example-todo-list | Continuation of the todo example using relations in LoopBack 4 |
| [example-todo](https://github.com/strongloop/loopback-next/tree/master/examples/todo) | @loopback/example-todo | A basic tutorial for getting started with Loopback 4 |
| [express-middleware](https://github.com/strongloop/loopback-next/tree/master/packages/express-middleware) | @loopback/express-middleware | Extensions to manage Express middleware |
| [http-caching-proxy](https://github.com/strongloop/loopback-next/tree/master/packages/http-caching-proxy) | @loopback/http-caching-proxy | A caching HTTP proxy for integration tests. NOT SUITABLE FOR PRODUCTION USE! |
| [http-server](https://github.com/strongloop/loopback-next/tree/master/packages/http-server) | @loopback/http-server | A wrapper for creating HTTP/HTTPS servers |
| [metadata](https://github.com/strongloop/loopback-next/tree/master/packages/metadata) | @loopback/metadata | Utilities to help developers implement TypeScript decorators, define/merge metadata, and inspect metadata |
Expand Down
1 change: 1 addition & 0 deletions docs/site/Reserved-binding-keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,4 @@ the prefix. Example: `@loopback/authentication` component uses the prefix
- [RestBindings](https://loopback.io/doc/en/lb4/apidocs.rest.restbindings.html)
- [RestBindings.Http](https://loopback.io/doc/en/lb4/apidocs.rest.http.html)
- [RestBindings.SequenceActions](https://loopback.io/doc/en/lb4/apidocs.rest.sequenceactions.html)
- [ExpressBindings](https://loopback.io/doc/en/lb4/apidocs.express-middleware.expressbindings.html)
25 changes: 25 additions & 0 deletions packages/express-middleware/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) IBM Corp. 2017,2019. All Rights Reserved.
Node module: @loopback/express-middleware
This project is licensed under the MIT License, full text below.

--------

MIT license

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
129 changes: 129 additions & 0 deletions packages/express-middleware/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# @loopback/express-middleware

[Express middleware](https://expressjs.com/en/guide/using-middleware.html) are
key building blocks for Express applications. Simple APIs are provided by
Express to set up middleware. It works for applications where the middleware
chain registration can be centralized, such as:

```js
app.use(middlewareHandler1);
app.use(middlewareHandler2);
// ...
app.use(middlewareHandlerN);
```

The middleware handlers will be executed by Express in the order of `app.use()`
is called. There are obvious limitations of this approach if your application
allows multiple modules to contribute middleware.

1. It's hard to align middleware in the right order
2. It's hard to separate configuration of middleware

This module introduces a simple extension that utilizes LoopBack 4's inversion
of controller (Ioc) dependency injection (DI) container offered by
`@loopback/context`.

## Overview

We introduce `MiddlewareRegistry` to manage middleware registration and provide
a handler function for Express applications.

1. `MiddlewareRegistry` allows us to bind middleware handlers with optional
settings such as `path` and `phase` as tags. Each binding is tagged with
`middleware` so that it can be discovered.

2. `MiddlewareRegistry` sorts the middleware entries using `phase`. The order of
phases can be configured.

3. `MiddlewareRegistry` exposes `requestHandler` function which is an Express
middleware handler function that can be mounted to Express applications.

4. `MiddlewareRegistry` observes binding events to keep track of latest list of
middleware and rebuilds the chain if necessary.

## Installation

To use this package, you'll need to install `@loopback/express-middleware`.

```sh
npm i @loopback/express-middleware
```

## Basic Use

### Register middleware handler

Handler functions compatible with Express middleware can be registered as
follows:

```ts
const middlewareRegistry = new MiddlewareRegistry();
middlewareRegistry.middleware(cors(), {phase: 'cors'});
const helloRoute: RequestHandler = (req, res, next) => {
res.setHeader('content-type', 'text/plain');
res.send('Hello world!');
};
middlewareRegistry.middleware(helloRoute, {phase: 'route', path: '/api'});
```

Please note we allow `phase` to be set for a given middleware.

### Register middleware provider class

To leverage dependency injection, middleware can be wrapped as a provider class.
For example:

```ts
@middleware({phase: 'log', name: 'logger'})
class LogMiddlewareProvider implements Provider<RequestHandler> {
constructor(
// Make it possible to inject middleware options
@inject('middleware.logger.options', {optional: true})
private options: Record<string, string> = {},
) {}

value(): RequestHandler {
/** We use wrap existing express middleware here too
* such as:
* const m = require('existingExpressMiddleware');
* return m(this.options);
*/
return (req, res, next) => {
recordReq(req, this.options.name || 'logger');
next();
};
}
}
```

Then it can be configured and registered to the express context:

```ts
middlewareRegistry.middlewareProvider(LogMiddlewareProvider);
middlewareRegistry.bind('middleware.logger.options').to({name: 'my-logger'});
```

### Mount to Express application

```ts
const expressApp = express();
expressApp.use(middlewareRegistry.requestHandler);
```

## Contributions

- [Guidelines](https://github.com/strongloop/loopback-next/blob/master/docs/CONTRIBUTING.md)
- [Join the team](https://github.com/strongloop/loopback-next/issues/110)

## Tests

Run `npm test` from the root folder.

## Contributors

See
[all contributors](https://github.com/strongloop/loopback-next/graphs/contributors).

## License

MIT
7 changes: 7 additions & 0 deletions packages/express-middleware/docs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"content": [
"index.ts",
"src/*"
],
"codeSectionDepth": 4
}
6 changes: 6 additions & 0 deletions packages/express-middleware/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2019. All Rights Reserved.
// Node module: @loopback/express-middleware
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './dist';
6 changes: 6 additions & 0 deletions packages/express-middleware/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2019. All Rights Reserved.
// Node module: @loopback/express-middleware
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

module.exports = require('./dist');
8 changes: 8 additions & 0 deletions packages/express-middleware/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright IBM Corp. 2019. All Rights Reserved.
// Node module: @loopback/express-middleware
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

// DO NOT EDIT THIS FILE
// Add any additional (re)exports to src/index.ts instead.
export * from './src';
Loading

0 comments on commit 3a9de17

Please sign in to comment.