@fastify/express 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "github-actions"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "monthly"
7
+ open-pull-requests-limit: 10
8
+
9
+ - package-ecosystem: "npm"
10
+ directory: "/"
11
+ schedule:
12
+ interval: "weekly"
13
+ open-pull-requests-limit: 10
@@ -0,0 +1,21 @@
1
+ # Number of days of inactivity before an issue becomes stale
2
+ daysUntilStale: 15
3
+ # Number of days of inactivity before a stale issue is closed
4
+ daysUntilClose: 7
5
+ # Issues with these labels will never be considered stale
6
+ exemptLabels:
7
+ - "discussion"
8
+ - "feature request"
9
+ - "bug"
10
+ - "help wanted"
11
+ - "plugin suggestion"
12
+ - "good first issue"
13
+ # Label to use when marking an issue as stale
14
+ staleLabel: stale
15
+ # Comment to post when marking an issue as stale. Set to `false` to disable
16
+ markComment: >
17
+ This issue has been automatically marked as stale because it has not had
18
+ recent activity. It will be closed if no further activity occurs. Thank you
19
+ for your contributions.
20
+ # Comment to post when closing a stale issue. Set to `false` to disable
21
+ closeComment: false
@@ -0,0 +1,49 @@
1
+ name: CI
2
+ 'on':
3
+ push:
4
+ paths-ignore:
5
+ - docs/**
6
+ - '*.md'
7
+ pull_request:
8
+ paths-ignore:
9
+ - docs/**
10
+ - '*.md'
11
+ jobs:
12
+ test:
13
+ runs-on: ${{ matrix.os }}
14
+ strategy:
15
+ matrix:
16
+ node-version:
17
+ - 10
18
+ - 12
19
+ - 14
20
+ - 16
21
+ os:
22
+ - macos-latest
23
+ - ubuntu-latest
24
+ - windows-latest
25
+ steps:
26
+ - uses: actions/checkout@v3
27
+ - name: Use Node.js
28
+ uses: actions/setup-node@v3
29
+ with:
30
+ node-version: ${{ matrix.node-version }}
31
+ - name: Install Dependencies
32
+ run: |
33
+ npm install --ignore-scripts
34
+ - name: Run Tests
35
+ run: |
36
+ npm test
37
+ automerge:
38
+ needs: test
39
+ runs-on: ubuntu-latest
40
+ permissions:
41
+ pull-requests: write
42
+ contents: write
43
+ steps:
44
+ - uses: fastify/github-action-merge-dependabot@v3
45
+ if: >-
46
+ ${{ github.actor == 'dependabot[bot]' && github.event_name ==
47
+ 'pull_request' }}
48
+ with:
49
+ github-token: ${{ secrets.GITHUB_TOKEN }}
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Fastify
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,207 @@
1
+ # fastify-express
2
+
3
+ ![CI](https://github.com/fastify/fastify-express/workflows/CI/badge.svg)
4
+ [![NPM version](https://img.shields.io/npm/v/fastify-express.svg?style=flat)](https://www.npmjs.com/package/fastify-express)
5
+ [![Known Vulnerabilities](https://snyk.io/test/github/fastify/fastify-express/badge.svg)](https://snyk.io/test/github/fastify/fastify-express)
6
+ [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)
7
+
8
+ This plugin adds full [Express](http://expressjs.com) compatibility to Fastify, it exposes the same `use` function of Express, and it allows you to use any Express middleware or application.<br/>
9
+
10
+ | **Note** | This plugin should not be used as a long-term solution, it aims to help you have a smooth transition from Express to Fastify, but you should migrate your Express specific code to Fastify over time. |
11
+ | ---- | :---- |
12
+
13
+ ## Install
14
+ ```
15
+ npm i fastify-express
16
+ ```
17
+
18
+ ## Usage
19
+ Register the plugin and start using your Express middlewares.
20
+ ```js
21
+ const Fastify = require('fastify')
22
+
23
+ async function build () {
24
+ const fastify = Fastify()
25
+ await fastify.register(require('fastify-express'))
26
+ // do you know we also have cors support?
27
+ // https://github.com/fastify/fastify-cors
28
+ fastify.use(require('cors')())
29
+ // express.Application is also accessible
30
+ fastify.express.disabled('x-powered-by') // true
31
+ return fastify
32
+ }
33
+
34
+ build()
35
+ .then(fastify => fastify.listen(3000))
36
+ .catch(console.log)
37
+ ```
38
+
39
+ ### Add a complete application
40
+
41
+ You can register an entire Express application and make it work with Fastify. Remember, `fastify-express` is just `express` under the covers and requires the same body parsers as you'd use in `express`.
42
+
43
+ ```js
44
+ // index.js
45
+ const fastify = require('fastify')()
46
+ const express = require('express')
47
+ const router = express.Router()
48
+
49
+ router.use(function (req, res, next) {
50
+ res.setHeader('x-custom', true)
51
+ next()
52
+ })
53
+
54
+ router.get('/hello', (req, res) => {
55
+ res.status(201)
56
+ res.json({ hello: 'world' })
57
+ })
58
+
59
+ router.get('/foo', (req, res) => {
60
+ res.status(400)
61
+ res.json({ foo: 'bar' })
62
+ })
63
+
64
+ router.patch('/bar', (req, res) => {
65
+ if (!req.body || Object.keys(req.body).length === 0) {
66
+ res.status(400)
67
+ res.json({ msg: 'no req.body'})
68
+ } else {
69
+ res.status(200)
70
+ res.json(req.body)
71
+ }
72
+ })
73
+
74
+ router.use('*', (req, res) => {
75
+ res.status(404)
76
+ res.json({ msg: 'not found'})
77
+ })
78
+
79
+ fastify.register(require('fastify-express'))
80
+ .after(() => {
81
+ fastify.use(express.urlencoded({extended: false})) // for Postman x-www-form-urlencoded
82
+ fastify.use(express.json())
83
+
84
+ fastify.use(router)
85
+ })
86
+
87
+ fastify.listen(3000, console.log)
88
+ ```
89
+
90
+ #### Testing Your App
91
+ Run `node index.js` to start your server. Then run the following commands to ensure your server is working. Use the optional `-v` flag in curl for verbose output.
92
+
93
+ ```bash
94
+ me@computer ~ % curl -X GET http://localhost:3000/hello
95
+ {"hello":"world"}%
96
+ me@computer ~ % curl -X GET http://localhost:3000/foo
97
+ {"foo":"bar"}%
98
+ me@computer ~ % curl -X GET http://localhost:3000/bar
99
+ {"msg":"not found"}%
100
+ me@computer ~ % curl -X PATCH -H 'content-type:application/json' http://localhost:3000/bar
101
+ {"msg":"no req.body"}%
102
+ me@computer ~ % curl -X PATCH -H 'content-type:application/json' -d '{"foo2":"bar2"}' http://localhost:3000/bar
103
+ {"foo2":"bar2"}%
104
+ ```
105
+
106
+ ### Encapsulation support
107
+
108
+ The encapsulation works as usual with Fastify, you can register the plugin in a subsystem and your express code will work only inside there, or you can declare the express plugin top level and register a middleware in a nested plugin, and the middleware will be executed only for the nested routes of the specific plugin.
109
+
110
+ *Register the plugin in its own subsystem:*
111
+ ```js
112
+ const fastify = require('fastify')()
113
+
114
+ fastify.register(subsystem)
115
+
116
+ async function subsystem (fastify, opts) {
117
+ await fastify.register(require('fastify-express'))
118
+ fastify.use(require('cors')())
119
+ }
120
+ ```
121
+
122
+ *Register a middleware in a specific plugin:*
123
+ ```js
124
+ const fastify = require('fastify')()
125
+
126
+ fastify
127
+ .register(require('fastify-express'))
128
+ .register(subsystem)
129
+
130
+ async function subsystem (fastify, opts) {
131
+ fastify.use(require('cors')())
132
+ }
133
+ ```
134
+
135
+ ### Hooks and middlewares
136
+
137
+ Every registered middleware will be run during the `onRequest` hook phase, so the registration order is important.
138
+ Take a look at the [Lifecycle](https://www.fastify.io/docs/latest/Lifecycle/) documentation page to understand better how every request is executed.
139
+
140
+ ```js
141
+ const fastify = require('fastify')()
142
+
143
+ fastify
144
+ .register(require('fastify-express'))
145
+ .register(subsystem)
146
+
147
+ async function subsystem (fastify, opts) {
148
+ fastify.addHook('onRequest', async (req, reply) => {
149
+ console.log('first')
150
+ })
151
+
152
+ fastify.use((req, res, next) => {
153
+ console.log('second')
154
+ next()
155
+ })
156
+
157
+ fastify.addHook('onRequest', async (req, reply) => {
158
+ console.log('third')
159
+ })
160
+ }
161
+ ```
162
+
163
+ ### Restrict middleware execution to a certain path(s)
164
+
165
+ If you need to run a middleware only under certain path(s), just pass the path as first parameter to use and you are done!
166
+
167
+ ```js
168
+ const fastify = require('fastify')()
169
+ const path = require('path')
170
+ const serveStatic = require('serve-static')
171
+
172
+ fastify
173
+ .register(require('fastify-express'))
174
+ .register(subsystem)
175
+
176
+ async function subsystem (fastify, opts) {
177
+ // Single path
178
+ fastify.use('/css', serveStatic(path.join(__dirname, '/assets')))
179
+
180
+ // Wildcard path
181
+ fastify.use('/css/*', serveStatic(path.join(__dirname, '/assets')))
182
+
183
+ // Multiple paths
184
+ fastify.use(['/css', '/js'], serveStatic(path.join(__dirname, '/assets')))
185
+ }
186
+ ```
187
+
188
+ ## TypeScript support
189
+
190
+ To use this module with TypeScript, make sure to install `@types/express`.
191
+
192
+ You will need to add `"types": ["fastify-express"]` to your tsconfig.json file when using `require` to import the plugin.
193
+
194
+ ## Middlewares alternatives
195
+
196
+ Fastify offers some alternatives to the most commonly used middlewares, following, you can find a list.
197
+
198
+ | Express Middleware | Fastify Plugin |
199
+ | ------------- |---------------|
200
+ | [`helmet`](https://github.com/helmetjs/helmet) | [`fastify-helmet`](https://github.com/fastify/fastify-helmet) |
201
+ | [`cors`](https://github.com/expressjs/cors) | [`fastify-cors`](https://github.com/fastify/fastify-cors) |
202
+ | [`serve-static`](https://github.com/expressjs/serve-static) | [`fastify-static`](https://github.com/fastify/fastify-static) |
203
+
204
+ ## License
205
+
206
+ Licensed under [MIT](./LICENSE).<br/>
207
+ [`express` license](https://github.com/expressjs/express/blob/master/LICENSE)
package/index.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { Application } from 'express'
2
+ import { FastifyPluginCallback } from 'fastify'
3
+
4
+ declare module 'fastify' {
5
+ interface FastifyInstance {
6
+ /**
7
+ * Express middleware function
8
+ */
9
+ use: Application['use']
10
+
11
+ /**
12
+ * Express application instance
13
+ */
14
+ express: Application
15
+ }
16
+ }
17
+
18
+ export const fastifyExpress: FastifyPluginCallback
19
+
20
+ export default fastifyExpress
package/index.js ADDED
@@ -0,0 +1,83 @@
1
+ 'use strict'
2
+
3
+ const fp = require('fastify-plugin')
4
+ const symbols = require('fastify/lib/symbols')
5
+ const Express = require('express')
6
+ const kMiddlewares = Symbol('fastify-express-middlewares')
7
+
8
+ function expressPlugin (fastify, options, next) {
9
+ fastify.decorate('use', use)
10
+ fastify[kMiddlewares] = []
11
+ fastify.decorate('express', Express())
12
+ fastify.express.disable('x-powered-by')
13
+
14
+ fastify
15
+ .addHook('onRequest', enhanceRequest)
16
+ .addHook('onRequest', runConnect)
17
+ .addHook('onRegister', onRegister)
18
+
19
+ function use (path, fn) {
20
+ if (typeof path === 'string') {
21
+ const prefix = this[symbols.kRoutePrefix]
22
+ path = prefix + (path === '/' && prefix.length > 0 ? '' : path)
23
+ }
24
+ this[kMiddlewares].push([path, fn])
25
+ if (fn == null) {
26
+ this.express.use(path)
27
+ } else {
28
+ this.express.use(path, fn)
29
+ }
30
+ return this
31
+ }
32
+
33
+ function enhanceRequest (req, reply, next) {
34
+ req.raw.originalUrl = req.raw.url
35
+ req.raw.id = req.id
36
+ req.raw.hostname = req.hostname
37
+ req.raw.ip = req.ip
38
+ req.raw.ips = req.ips
39
+ req.raw.log = req.log
40
+ reply.raw.log = req.log
41
+
42
+ const originalProtocol = req.raw.protocol
43
+ // Make it lazy as it does a bit of work
44
+ Object.defineProperty(req.raw, 'protocol', {
45
+ get () {
46
+ // added in Fastify@3.5, so handle it missing
47
+ return req.protocol || originalProtocol
48
+ }
49
+ })
50
+
51
+ next()
52
+ }
53
+
54
+ function runConnect (req, reply, next) {
55
+ if (this[kMiddlewares].length > 0) {
56
+ for (const [headerName, headerValue] of Object.entries(reply.getHeaders())) {
57
+ reply.raw.setHeader(headerName, headerValue)
58
+ }
59
+
60
+ this.express(req.raw, reply.raw, next)
61
+ } else {
62
+ next()
63
+ }
64
+ }
65
+
66
+ function onRegister (instance) {
67
+ const middlewares = instance[kMiddlewares].slice()
68
+ instance[kMiddlewares] = []
69
+ instance.decorate('express', Express())
70
+ instance.express.disable('x-powered-by')
71
+ instance.decorate('use', use)
72
+ for (const middleware of middlewares) {
73
+ instance.use(...middleware)
74
+ }
75
+ }
76
+
77
+ next()
78
+ }
79
+
80
+ module.exports = fp(expressPlugin, {
81
+ fastify: '>=3.0.0',
82
+ name: 'fastify-express'
83
+ })
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@fastify/express",
3
+ "version": "1.0.0",
4
+ "description": "Express compatibility layer for Fastify",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "scripts": {
8
+ "test": "standard && tap --no-coverage test/*.test.js && tsd"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/fastify/fastify-express.git"
13
+ },
14
+ "keywords": [
15
+ "fastify",
16
+ "express",
17
+ "middlewares",
18
+ "use",
19
+ "compatibility"
20
+ ],
21
+ "author": "Tomas Della Vedova - @delvedor (http://delved.org)",
22
+ "license": "MIT",
23
+ "bugs": {
24
+ "url": "https://github.com/fastify/fastify-express/issues"
25
+ },
26
+ "homepage": "https://github.com/fastify/fastify-express#readme",
27
+ "devDependencies": {
28
+ "@types/express": "^4.17.1",
29
+ "@types/node": "*",
30
+ "cors": "^2.8.5",
31
+ "fastify": "^3.0.0",
32
+ "helmet": "^5.0.0",
33
+ "passport": "^0.5.1",
34
+ "passport-http-bearer": "^1.0.1",
35
+ "serve-static": "^1.14.1",
36
+ "simple-get": "^4.0.0",
37
+ "standard": "^17.0.0",
38
+ "tap": "^16.0.0",
39
+ "tsd": "^0.20.0"
40
+ },
41
+ "dependencies": {
42
+ "express": "^4.17.1",
43
+ "fastify-plugin": "^3.0.0"
44
+ },
45
+ "engines": {
46
+ "node": ">=10.0.0"
47
+ },
48
+ "tsd": {
49
+ "directory": "test/types"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ }
54
+ }