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

fix: request set headers #2817

Merged
merged 11 commits into from
Aug 9, 2021
6 changes: 6 additions & 0 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,12 @@ Object.defineProperties(Request.prototype, {
headers: {
get () {
return this.raw.headers
},
set (headers) {
const headerPairs = Object.entries(headers)
for (const [header, value] of headerPairs) {
this.raw.headers[header] = value
}
}
}
})
Expand Down
32 changes: 32 additions & 0 deletions test/schema-special-usage.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const { test } = require('tap')
const Joi = require('@hapi/joi')
const Fastify = require('..')
const ajvMergePatch = require('ajv-merge-patch')

Expand Down Expand Up @@ -221,3 +222,34 @@ test('Should handle $patch keywords in body', t => {
})
})
})

test('JOI validation overwrite request headers', t => {
t.plan(3)
const schemaValidator = ({ schema }) => data => {
const validationResult = schema.validate(data)
return validationResult
}

const fastify = Fastify()
fastify.setValidatorCompiler(schemaValidator)

fastify.get('/', {
schema: {
headers: Joi.object({
'user-agent': Joi.string().required(),
host: Joi.string().required()
})
}
}, (request, reply) => {
reply.send(request.headers)
})

fastify.inject('/', (err, res) => {
t.error(err)
t.equals(res.statusCode, 200)
t.deepEquals(res.json(), {
'user-agent': 'lightMyRequest',
host: 'localhost:80'
})
})
})