Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC] Introduce express middleware extension point #2434

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,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/model-api-builder/* @bajtos @nabdelgadir
packages/openapi-spec-builder/* @bajtos @raymondfeng
Expand Down
1 change: 1 addition & 0 deletions docs/site/MONOREPO.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ The [loopback-next](https://github.com/strongloop/loopback-next) repository uses
| [example-todo](https://github.com/strongloop/loopback-next/tree/master/examples/todo) | @loopback/example-todo | A basic tutorial for getting started with Loopback 4 |
| [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 |
| [express-middleware](https://github.com/strongloop/loopback-next/tree/master/packages/express-middleware) | @loopback/express-middleware | Extensions to manage Express middleware |
| [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 |
| [model-api-builder](https://github.com/strongloop/loopback-next/tree/master/packages/model-api-builder) | @loopback/model-api-builder | Types and helpers for packages contributing Model API builders. |
| [openapi-spec-builder](https://github.com/strongloop/loopback-next/tree/master/packages/openapi-spec-builder) | @loopback/openapi-spec-builder | Builders to create OpenAPI (Swagger) specification documents in tests |
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.
128 changes: 128 additions & 0 deletions packages/express-middleware/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# @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(
@config()
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.configure('middleware.logger').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
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