-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(express-middleware): add an extension point for express middleware
- Loading branch information
1 parent
c3d8007
commit eb4c08e
Showing
17 changed files
with
680 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# @loopback/express-middleware | ||
|
||
## Overview | ||
|
||
## Installation | ||
|
||
To use this package, you'll need to install `@loopback/express-middleware`. | ||
|
||
```sh | ||
npm i @loopback/express-middleware | ||
``` | ||
|
||
## Basic Use | ||
|
||
## 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"content": [ | ||
"index.ts", | ||
"src/*" | ||
], | ||
"codeSectionDepth": 4 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} |
106 changes: 106 additions & 0 deletions
106
packages/express-middleware/src/__tests__/acceptance/express-context.acceptance.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {ExpressBindings} from '../../keys'; | ||
import {middleware} from '../../middleware'; | ||
|
||
describe('HttpHandler mounted as an express router', () => { | ||
let client: Client; | ||
let expressApp: express.Application; | ||
let context: 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( | ||
@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 = []; | ||
context = new ExpressContext(); | ||
context.bind(ExpressBindings.EXPRESS_MIDDLEWARE_REGISTRY_OPTIONS).to({ | ||
phasesByOrder: ['log', 'cors', 'auth', 'route'], | ||
}); | ||
const auth: RequestHandler = (req, res, next) => { | ||
recordReq(req, 'auth'); | ||
next(); | ||
}; | ||
context.middleware(auth, {phase: 'auth', path: '/hello'}); | ||
context.middleware(cors(), {phase: 'cors'}); | ||
const route: RequestHandler = (req, res, next) => { | ||
recordReq(req, 'route'); | ||
res.setHeader('content-type', 'text/plain'); | ||
res.send('Hello world!'); | ||
}; | ||
context.middleware(route, {phase: 'route'}); | ||
context.middlewareProvider(LogMiddlewareProvider); | ||
context.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(context.requestHandler); | ||
} | ||
|
||
function givenClient() { | ||
client = createClientForHandler(expressApp); | ||
} | ||
}); |
91 changes: 91 additions & 0 deletions
91
packages/express-middleware/src/__tests__/unit/middleware-registry.unit.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
// Copyright IBM Corp. 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 {Context, inject, Provider} from '@loopback/context'; | ||
import { | ||
expect, | ||
ShotRequestOptions, | ||
stubExpressContext, | ||
} from '@loopback/testlab'; | ||
import {Request, RequestHandler, Response} from 'express'; | ||
import {asMiddlewareBinding, MiddlewareRegistry, MiddlewareSpec} from '../..'; | ||
|
||
describe('MiddlewareRegistry', () => { | ||
const DUMMY_RESPONSE = ({ | ||
setHeader: () => {}, | ||
end: () => {}, | ||
} as unknown) as Response; | ||
let ctx: Context; | ||
let registry: MiddlewareRegistry; | ||
let events: string[]; | ||
|
||
beforeEach(givenContext); | ||
beforeEach(givenMiddlewareRegistry); | ||
|
||
it('builds an express router', async () => { | ||
registry.setPhasesByOrder(['cors', 'auth', 'route', 'final']); | ||
|
||
givenMiddleware('rest', {phase: 'route', path: '/api'}); | ||
givenMiddlewareProvider('cors', {phase: 'cors'}); | ||
givenMiddleware('token', {phase: 'auth'}); | ||
await testRouter('get', '/api/orders'); | ||
expect(events).to.eql(['token: GET /api/orders', 'rest: GET /orders']); | ||
}); | ||
|
||
function givenContext() { | ||
events = []; | ||
ctx = new Context('app'); | ||
} | ||
|
||
async function givenMiddlewareRegistry() { | ||
ctx.bind('middleware.registry').toClass(MiddlewareRegistry); | ||
registry = await ctx.get('middleware.registry'); | ||
} | ||
|
||
function givenMiddleware(name: string, spec?: MiddlewareSpec) { | ||
const middleware: RequestHandler = (req, res, next) => { | ||
events.push(`${name}: ${req.method} ${req.url}`); | ||
next(); | ||
}; | ||
ctx | ||
.bind(`middleware.${name}`) | ||
.to(middleware) | ||
.apply(asMiddlewareBinding(spec)); | ||
} | ||
|
||
function givenMiddlewareProvider(moduleName: string, spec?: MiddlewareSpec) { | ||
class MiddlewareProvider implements Provider<MiddlewareProvider> { | ||
private middlewareModule: Function; | ||
constructor( | ||
@inject(`middleware.${moduleName}.options`, {optional: true}) | ||
private options: object = {}, | ||
) { | ||
this.middlewareModule = require(moduleName); | ||
} | ||
|
||
value() { | ||
return this.middlewareModule(this.options); | ||
} | ||
} | ||
ctx | ||
.bind(`middleware.${moduleName}`) | ||
.toProvider(MiddlewareProvider) | ||
.apply(asMiddlewareBinding(spec)); | ||
} | ||
|
||
function givenRequest(options?: ShotRequestOptions): Request { | ||
return stubExpressContext(options).request; | ||
} | ||
|
||
async function testRouter(method: string, url: string) { | ||
const router = await registry.createExpressRouter(); | ||
await new Promise<void>((resolve, reject) => { | ||
router(givenRequest({url, method}), DUMMY_RESPONSE, err => { | ||
if (err) reject(err); | ||
else resolve(); | ||
}); | ||
}); | ||
} | ||
}); |
Oops, something went wrong.