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
  • Loading branch information
raymondfeng committed Mar 6, 2019
1 parent c3d8007 commit 2daf3f1
Show file tree
Hide file tree
Showing 17 changed files with 786 additions and 2 deletions.
4 changes: 2 additions & 2 deletions greenkeeper.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"packages/cli/package.json",
"packages/context/package.json",
"packages/core/package.json",
"packages/express-middleware/package.json",
"packages/http-caching-proxy/package.json",
"packages/http-server/package.json",
"packages/metadata/package.json",
Expand All @@ -34,6 +35,5 @@
"sandbox/example/package.json"
]
}
},
"ignore": ["@types/node"]
}
}
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 `ExpressContext` to manage middleware registration and provide a
handler function for Express applications.

1. `ExpressContext` 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. `ExpressContext` sorts the middleware entries using `phase`. The order of
phases can be configured.

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

4. `ExpressContext` 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 expressCtx = new ExpressContext();
expressCtx.middleware(cors(), {phase: 'cors'});
const helloRoute: RequestHandler = (req, res, next) => {
res.setHeader('content-type', 'text/plain');
res.send('Hello world!');
};
expressCtx.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
expressCtx.middlewareProvider(LogMiddlewareProvider);
expressCtx.bind('middleware.logger.options').to({name: 'my-logger'});
```

### Mount to Express application

```ts
const expressApp = express();
expressApp.use(expressCtx.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';
50 changes: 50 additions & 0 deletions packages/express-middleware/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "@loopback/express-middleware",
"version": "1.0.0-1",
"description": "LoopBack extension for Express middleware",
"engines": {
"node": ">=8.9"
},
"scripts": {
"acceptance": "lb-mocha \"dist/__tests__/acceptance/**/*.js\"",
"build:apidocs": "lb-apidocs",
"build": "lb-tsc es2017 --outDir dist",
"clean": "lb-clean loopback-express-middleware*.tgz dist package api-docs",
"pretest": "npm run build",
"integration": "lb-mocha \"dist/__tests__/integration/**/*.js\"",
"test": "lb-mocha \"dist/__tests__/**/*.js\"",
"unit": "lb-mocha \"dist/__tests__/unit/**/*.js\"",
"verify": "npm pack && tar xf loopback-express-middleware*.tgz && tree package && npm run clean"
},
"author": "IBM Corp.",
"copyright.owner": "IBM Corp.",
"license": "MIT",
"dependencies": {
"@loopback/context": "^1.6.0",
"debug": "^4.1.1",
"express": "^4.16.4",
"@types/express": "^4.11.1",
"@types/express-serve-static-core": "^4.16.0"
},
"devDependencies": {
"@loopback/build": "^1.3.1",
"@loopback/testlab": "^1.0.7",
"@loopback/tslint-config": "^2.0.1",
"@types/cors": "^2.8.4",
"@types/debug": "^4.1.2",
"@types/node": "^10.11.2",
"cors": "^2.8.5"
},
"files": [
"README.md",
"index.js",
"index.d.ts",
"dist",
"src",
"!*/__tests__"
],
"repository": {
"type": "git",
"url": "https://github.com/strongloop/loopback-next.git"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/rest
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {inject, Provider} from '@loopback/context';
import {Client, createClientForHandler, expect} from '@loopback/testlab';
import * as cors from 'cors';
import * as express from 'express';
import {RequestHandler} from 'express-serve-static-core';
import {ExpressContext} from '../../express-context';
import {middleware} from '../../middleware';

describe('HttpHandler mounted as an express router', () => {
let client: Client;
let expressApp: express.Application;
let expressCtx: ExpressContext;
let events: string[];

beforeEach(givenExpressContext);
beforeEach(givenExpressApp);
beforeEach(givenClient);

it('handles simple "GET /hello" requests', async () => {
await client
.get('/hello')
.expect(200)
.expect('Hello world!');
expect(events).to.eql([
'my-logger: get /hello',
'auth: get /hello',
'route: get /hello',
]);
});

it('handles simple "GET /greet" requests', async () => {
await client
.get('/greet')
.expect(200)
.expect('Hello world!');
// No 'auth: get /greet' is recorded as the path does not match
expect(events).to.eql(['my-logger: get /greet', 'route: get /greet']);
});

/**
* This class illustrates how to use DI for express middleware
*/
@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();
};
}
}

async function givenExpressContext() {
events = [];
expressCtx = new ExpressContext();
expressCtx.setMiddlewareRegistryOptions({
phasesByOrder: ['log', 'cors', 'auth', 'route'],
});
const auth: RequestHandler = (req, res, next) => {
recordReq(req, 'auth');
next();
};
expressCtx.middleware(auth, {phase: 'auth', path: '/hello'});
expressCtx.middleware(cors(), {phase: 'cors'});
const route: RequestHandler = (req, res, next) => {
recordReq(req, 'route');
res.setHeader('content-type', 'text/plain');
res.send('Hello world!');
};
expressCtx.middleware(route, {phase: 'route'});
expressCtx.middlewareProvider(LogMiddlewareProvider);
expressCtx.bind('middleware.logger.options').to({name: 'my-logger'});
}

function recordReq(req: express.Request, name: string) {
events.push(`${name}: ${req.method.toLowerCase()} ${req.originalUrl}`);
}

/**
* Create an express app
*/
function givenExpressApp() {
expressApp = express();
expressApp.use(expressCtx.requestHandler);
}

function givenClient() {
client = createClientForHandler(expressApp);
}
});
Loading

0 comments on commit 2daf3f1

Please sign in to comment.