@fastify/express 2.2.0 → 3.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.
package/.gitattributes ADDED
@@ -0,0 +1,2 @@
1
+ # Set default behavior to automatically convert line endings
2
+ * text=auto eol=lf
@@ -2,6 +2,11 @@ name: CI
2
2
 
3
3
  on:
4
4
  push:
5
+ branches:
6
+ - main
7
+ - master
8
+ - next
9
+ - 'v*'
5
10
  paths-ignore:
6
11
  - 'docs/**'
7
12
  - '*.md'
package/README.md CHANGED
@@ -143,7 +143,7 @@ async function subsystem (fastify, opts) {
143
143
  ### Hooks and middlewares
144
144
 
145
145
  Every registered middleware will be run during the `onRequest` hook phase, so the registration order is important.
146
- Take a look at the [Lifecycle](https://www.fastify.io/docs/latest/Lifecycle/) documentation page to understand better how every request is executed.
146
+ Take a look at the [Lifecycle](https://fastify.dev/docs/latest/Reference/Lifecycle) documentation page to understand better how every request is executed.
147
147
 
148
148
  ```js
149
149
  const fastify = require('fastify')()
@@ -174,7 +174,7 @@ If you need to run a middleware only under certain path(s), just pass the path a
174
174
 
175
175
  ```js
176
176
  const fastify = require('fastify')()
177
- const path = require('path')
177
+ const path = require('node:path')
178
178
  const serveStatic = require('serve-static')
179
179
 
180
180
  fastify
@@ -193,6 +193,27 @@ async function subsystem (fastify, opts) {
193
193
  }
194
194
  ```
195
195
 
196
+ ### Wrap Express req in Proxy
197
+
198
+ It is possible to wrap the Express request object in a Proxy by passing `createProxyHandler` function to generate the Proxy handler. The function will receive the Fastify request object as the first parameter.
199
+
200
+ For example using Proxy to expose something from Fastify request into the Express request.
201
+
202
+ ```js
203
+ fastify.decorateRequest('welcomeMessage', 'Hello World');
204
+ fastify.register(expressPlugin, {
205
+ createProxyHandler: fastifyRequest => ({
206
+ get (target, prop) {
207
+ if (prop === 'welcomeMessage') {
208
+ return fastifyRequest[prop]
209
+ }
210
+
211
+ return target[prop]
212
+ }
213
+ })
214
+ })
215
+ ```
216
+
196
217
  ## TypeScript support
197
218
 
198
219
  To use this module with TypeScript, make sure to install `@types/express`.
package/index.js CHANGED
@@ -6,7 +6,8 @@ const kMiddlewares = Symbol('fastify-express-middlewares')
6
6
 
7
7
  function fastifyExpress (fastify, options, next) {
8
8
  const {
9
- expressHook = 'onRequest'
9
+ expressHook = 'onRequest',
10
+ createProxyHandler
10
11
  } = options
11
12
 
12
13
  fastify.decorate('use', use)
@@ -34,13 +35,24 @@ function fastifyExpress (fastify, options, next) {
34
35
  }
35
36
 
36
37
  function enhanceRequest (req, reply, next) {
37
- req.raw.originalUrl = req.raw.url
38
+ // Allow attaching custom Proxy handlers to Express req
39
+ if (typeof createProxyHandler === 'function') {
40
+ req.raw = new Proxy(req.raw, createProxyHandler(req))
41
+ }
42
+
43
+ const { url } = req.raw
44
+ req.raw.originalUrl = url
38
45
  req.raw.id = req.id
39
46
  req.raw.hostname = req.hostname
40
47
  req.raw.ip = req.ip
41
48
  req.raw.ips = req.ips
42
49
  req.raw.log = req.log
43
50
  reply.raw.log = req.log
51
+ reply.raw.send = function send (...args) {
52
+ // Restore req.raw.url to its original value https://github.com/fastify/fastify-express/issues/11
53
+ req.raw.url = url
54
+ return reply.send.apply(reply, args)
55
+ }
44
56
 
45
57
  // backward compatibility for body-parser
46
58
  if (req.body) {
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@fastify/express",
3
- "version": "2.2.0",
3
+ "version": "3.0.0",
4
4
  "description": "Express compatibility layer for Fastify",
5
5
  "main": "index.js",
6
+ "type": "commonjs",
6
7
  "types": "types/index.d.ts",
7
8
  "scripts": {
8
9
  "lint": "standard",
@@ -34,14 +35,14 @@
34
35
  "body-parser": "^1.20.0",
35
36
  "cors": "^2.8.5",
36
37
  "fastify": "^4.0.0-rc.3",
37
- "helmet": "^6.0.0",
38
- "passport": "^0.6.0",
38
+ "helmet": "^7.0.0",
39
+ "passport": "^0.7.0",
39
40
  "passport-http-bearer": "^1.0.1",
40
41
  "serve-static": "^1.14.1",
41
42
  "simple-get": "^4.0.0",
42
43
  "standard": "^17.0.0",
43
44
  "tap": "^16.0.0",
44
- "tsd": "^0.24.1"
45
+ "tsd": "^0.31.0"
45
46
  },
46
47
  "dependencies": {
47
48
  "express": "^4.17.1",
@@ -578,7 +578,7 @@ test('Middleware chain (with errors) / 2', t => {
578
578
  })
579
579
 
580
580
  test('Send a response from a middleware', t => {
581
- t.plan(4)
581
+ t.plan(5)
582
582
 
583
583
  const fastify = Fastify()
584
584
 
@@ -602,8 +602,9 @@ test('Send a response from a middleware', t => {
602
602
  t.fail('We should not be here')
603
603
  })
604
604
 
605
- fastify.addHook('onSend', (req, reply, next) => {
606
- t.fail('We should not be here')
605
+ fastify.addHook('onSend', (req, reply, payload, next) => {
606
+ t.ok('called')
607
+ next(null, payload)
607
608
  })
608
609
 
609
610
  fastify.addHook('onResponse', (req, reply, next) => {
@@ -67,3 +67,121 @@ test('trust proxy protocol', (t) => {
67
67
  })
68
68
  })
69
69
  })
70
+
71
+ test('passing createProxyHandler sets up a Proxy with Express req', t => {
72
+ t.plan(8)
73
+ const testString = 'test proxy'
74
+
75
+ const fastify = Fastify()
76
+ fastify.register(expressPlugin, {
77
+ createProxyHandler: () => ({
78
+ set (target, prop, value) {
79
+ if (prop === 'customField') {
80
+ t.equal(value, testString)
81
+ }
82
+
83
+ return Reflect.set(target, prop, value)
84
+ },
85
+ get (target, prop) {
86
+ if (prop === 'customField') {
87
+ t.pass('get customField called')
88
+ }
89
+
90
+ return target[prop]
91
+ }
92
+ })
93
+ })
94
+ .after(() => {
95
+ fastify.use(function (req, res, next) {
96
+ req.customField = testString
97
+ t.equal(req.customField, testString)
98
+ next()
99
+ })
100
+ })
101
+
102
+ fastify.get('/', function (request, reply) {
103
+ reply.send({ hello: 'world' })
104
+ })
105
+
106
+ fastify.listen({ port: 0 }, err => {
107
+ t.error(err)
108
+
109
+ t.teardown(fastify.server.close.bind(fastify.server))
110
+
111
+ sget({
112
+ method: 'GET',
113
+ url: 'http://localhost:' + fastify.server.address().port
114
+ }, (err, response, body) => {
115
+ t.error(err)
116
+ t.equal(response.statusCode, 200)
117
+ t.equal(response.headers['content-length'], '' + body.length)
118
+ t.same(JSON.parse(body), { hello: 'world' })
119
+ })
120
+ })
121
+ })
122
+
123
+ test('createProxyHandler has access to Fastify request object', t => {
124
+ t.plan(12)
125
+ const startTestString = 'original'
126
+
127
+ const fastify = Fastify()
128
+ fastify.decorateRequest('getAndSetFastify', startTestString)
129
+ fastify.decorateRequest('getOnlyFastify', startTestString)
130
+
131
+ fastify.register(expressPlugin, {
132
+ createProxyHandler: fastifyReq => ({
133
+ set (target, prop, value) {
134
+ if (prop === 'getAndSetFastify') {
135
+ t.pass('set to Fastify called')
136
+ return Reflect.set(fastifyReq, prop, value)
137
+ } else if (prop === 'getOnlyFastify') {
138
+ return true
139
+ } else {
140
+ return Reflect.set(target, prop, value)
141
+ }
142
+ },
143
+ get (target, prop) {
144
+ if (prop === 'getAndSetFastify' || prop === 'getOnlyFastify') {
145
+ // Return something from Fastify req
146
+ t.pass('get from Fastify called')
147
+ return fastifyReq[prop]
148
+ }
149
+
150
+ return target[prop]
151
+ }
152
+ })
153
+ })
154
+ .after(() => {
155
+ fastify.use(function (req, res, next) {
156
+ t.equal(req.getAndSetFastify, startTestString)
157
+ t.equal(req.getOnlyFastify, startTestString)
158
+ req.getAndSetFastify = 'updated'
159
+ req.getOnlyFastify = 'updated'
160
+ next()
161
+ })
162
+ })
163
+
164
+ fastify.get('/', function (request, reply) {
165
+ // getOnlyFastify should change and getOnlyFastify should not
166
+ t.equal(request.getAndSetFastify, 'updated')
167
+ t.equal(request.getOnlyFastify, startTestString)
168
+
169
+ reply.send({ hello: 'world' })
170
+ })
171
+
172
+ fastify.listen({ port: 0 }, err => {
173
+ t.error(err)
174
+
175
+ t.teardown(fastify.server.close.bind(fastify.server))
176
+
177
+ sget({
178
+ method: 'GET',
179
+ url: 'http://localhost:' + fastify.server.address().port
180
+ }, (err, response, body) => {
181
+ t.error(err)
182
+ t.equal(response.statusCode, 200)
183
+ t.equal(response.headers['content-length'], '' + body.length)
184
+ t.same(JSON.parse(body), { hello: 'world' })
185
+ })
186
+ })
187
+ })
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { test } = require('tap')
4
4
  const Fastify = require('fastify')
5
+ const express = require('express')
5
6
  const expressPlugin = require('../index')
6
7
 
7
8
  test('onSend hook should receive valid request and reply objects if middleware fails', t => {
@@ -35,3 +36,37 @@ test('onSend hook should receive valid request and reply objects if middleware f
35
36
  t.equal(res.statusCode, 500)
36
37
  })
37
38
  })
39
+
40
+ test('request.url is not mutated between onRequest and onResponse', t => {
41
+ t.plan(4)
42
+ const fastify = Fastify()
43
+ const targetUrl = '/hubba/bubba'
44
+
45
+ fastify.addHook('onRequest', (request, _, next) => {
46
+ t.equal(request.url, targetUrl)
47
+ next()
48
+ })
49
+
50
+ fastify.addHook('onResponse', (request, _, next) => {
51
+ t.equal(request.url, targetUrl)
52
+ next()
53
+ })
54
+
55
+ fastify.register(expressPlugin).after(() => {
56
+ const mainRouter = express.Router()
57
+ const innerRouter = express.Router()
58
+ mainRouter.use('/hubba', innerRouter)
59
+ innerRouter.get('/bubba', (req, res) => {
60
+ res.sendStatus(200)
61
+ })
62
+ fastify.use(mainRouter)
63
+ })
64
+
65
+ fastify.inject({
66
+ method: 'GET',
67
+ url: targetUrl
68
+ }, (err, res) => {
69
+ t.error(err)
70
+ t.equal(res.statusCode, 200)
71
+ })
72
+ })
@@ -253,7 +253,7 @@ test('middlewares with prefix', t => {
253
253
  })
254
254
 
255
255
  test('res.end should block middleware execution', t => {
256
- t.plan(5)
256
+ t.plan(6)
257
257
 
258
258
  const instance = fastify()
259
259
  t.teardown(instance.close)
@@ -278,7 +278,8 @@ test('res.end should block middleware execution', t => {
278
278
  })
279
279
 
280
280
  instance.addHook('onSend', (req, reply, payload, next) => {
281
- t.fail('this should not be called')
281
+ t.ok('called')
282
+ next(null, payload)
282
283
  })
283
284
 
284
285
  instance.addHook('onResponse', (request, reply, next) => {
package/types/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Application } from 'express'
2
- import { FastifyPluginCallback } from 'fastify'
1
+ import { Application, Request } from 'express'
2
+ import { FastifyPluginCallback, FastifyRequest } from 'fastify'
3
3
 
4
4
  declare module 'fastify' {
5
5
  interface FastifyInstance {
@@ -21,6 +21,7 @@ declare namespace fastifyExpress {
21
21
 
22
22
  export interface FastifyExpressOptions {
23
23
  expressHook?: string;
24
+ createProxyHandler?: (fastifyReq: FastifyRequest) => ProxyHandler<Request>
24
25
  }
25
26
 
26
27
  export const fastifyExpress: FastifyExpress
@@ -1,4 +1,4 @@
1
- import Fastify from 'fastify'
1
+ import Fastify, { FastifyRequest } from 'fastify'
2
2
  import fastifyExpress from '..'
3
3
  import { expectType } from "tsd"
4
4
  import { Application } from 'express'
@@ -7,7 +7,13 @@ const app = Fastify()
7
7
 
8
8
  app.register(fastifyExpress)
9
9
  app.register(fastifyExpress, {
10
- expressHook: 'onRequest'
10
+ expressHook: 'onRequest',
11
+ createProxyHandler: (fastifyReq) => ({
12
+ set(target, prop, value) {
13
+ expectType<FastifyRequest>(fastifyReq)
14
+ return Reflect.set(target, prop, value)
15
+ }
16
+ })
11
17
  })
12
18
 
13
19
  expectType<Application>(app.express)
@@ -16,4 +22,4 @@ app.express.disable('x-powered-by')
16
22
 
17
23
  app.use('/world', (_req, res) => {
18
24
  res.sendStatus(200)
19
- })
25
+ })