Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@athenna/http",
"version": "5.54.0",
"version": "5.55.0",
"description": "The Athenna Http server. Built on top of fastify.",
"license": "MIT",
"author": "João Lenon <lenon@athenna.io>",
Expand Down
8 changes: 4 additions & 4 deletions src/context/Request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ export class Request extends Macroable {
* ```
*/
public get body(): any | any[] {
return this.request.body || {}
return this.request.zodParsed?.body || this.request.body || {}
}

/**
Expand All @@ -220,7 +220,7 @@ export class Request extends Macroable {
* ```
*/
public get params(): any {
return this.request.params || {}
return this.request.zodParsed?.params || this.request.params || {}
}

/**
Expand All @@ -232,7 +232,7 @@ export class Request extends Macroable {
* ```
*/
public get queries(): any {
return this.request.query || {}
return this.request.zodParsed?.query || this.request.query || {}
}

/**
Expand All @@ -244,7 +244,7 @@ export class Request extends Macroable {
* ```
*/
public get headers(): any {
return this.request.headers || {}
return this.request.zodParsed?.headers || this.request.headers || {}
}

/**
Expand Down
6 changes: 6 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
declare module 'fastify' {
interface FastifyRequest {
data: any
zodParsed?: {
body?: any
headers?: any
params?: any
query?: any
}
}

interface FastifyReply {
Expand Down
5 changes: 4 additions & 1 deletion src/providers/HttpServerProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ export class HttpServerProvider extends ServiceProvider {
public register() {
const fastifyOptions = Config.get<FastifyServerOptions>('http.fastify')

this.container.instance('Athenna/Core/HttpServer', new ServerImpl(fastifyOptions))
this.container.instance(
'Athenna/Core/HttpServer',
new ServerImpl(fastifyOptions)
)
}

public async shutdown() {
Expand Down
25 changes: 21 additions & 4 deletions src/router/RouteSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,21 +87,38 @@ export async function parseRequestWithZod(
schemas: RouteZodSchemas
) {
const requestSchemas = schemas.request
const parsed = req.zodParsed || {}

if (requestSchemas.body) {
req.body = await parseSchema(requestSchemas.body, req.body)
const body = await parseSchema(requestSchemas.body, req.body)

req.body = body
parsed.body = body
}

if (requestSchemas.headers) {
req.headers = await parseSchema(requestSchemas.headers, req.headers)
const headers = await parseSchema(requestSchemas.headers, req.headers)

req.headers = headers
parsed.headers = headers
}

if (requestSchemas.params) {
req.params = await parseSchema(requestSchemas.params, req.params)
const params = await parseSchema(requestSchemas.params, req.params)

req.params = params
parsed.params = params
}

if (requestSchemas.querystring) {
req.query = await parseSchema(requestSchemas.querystring, req.query)
const query = await parseSchema(requestSchemas.querystring, req.query)

req.query = query
parsed.query = query
}

if (Object.keys(parsed).length) {
req.zodParsed = parsed
}
}

Expand Down
12 changes: 8 additions & 4 deletions src/server/ServerImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export class ServerImpl extends Macroable {

this.fastify.decorateReply('body', null)
this.fastify.decorateRequest('data', null)
this.fastify.decorateRequest('zodParsed', null)
}

/**
Expand Down Expand Up @@ -310,7 +311,10 @@ export class ServerImpl extends Macroable {
}

if (zodSchemas) {
route.preValidation = [async req => parseRequestWithZod(req, zodSchemas)]
route.preHandler = [
async req => parseRequestWithZod(req, zodSchemas),
...this.toRouteHooks(route.preHandler)
]
}

if (options.data && Is.Array(route.preHandler)) {
Expand All @@ -325,9 +329,9 @@ export class ServerImpl extends Macroable {
}

if (zodSchemas) {
fastifyOptions.preValidation = [
...this.toRouteHooks(route.preValidation),
...this.toRouteHooks(fastifyOptions.preValidation)
fastifyOptions.preHandler = [
...this.toRouteHooks(route.preHandler),
...this.toRouteHooks(fastifyOptions.preHandler)
]
}

Expand Down
23 changes: 23 additions & 0 deletions tests/unit/context/RequestTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,29 @@ export default class RequestTest {
})
}

@Test()
public async shouldPreferZodParsedRequestValuesWhenAvailable({ assert }: Context) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.request.zodParsed = {
body: { enabled: true },
headers: { 'x-enabled': false },
params: { id: 1 },
query: { enabled: true }
}

const ctx = { request: new Request(this.request) }

assert.deepEqual(ctx.request.body, { enabled: true })
assert.deepEqual(ctx.request.headers, { 'x-enabled': false })
assert.deepEqual(ctx.request.params, { id: 1 })
assert.deepEqual(ctx.request.queries, { enabled: true })
assert.isTrue(ctx.request.input('enabled'))
assert.isFalse(ctx.request.header('x-enabled'))
assert.equal(ctx.request.param('id'), 1)
assert.isTrue(ctx.request.query('enabled'))
}

@Test()
public async shouldBeAbleToGetTheServerPortFromRequest({ assert }: Context) {
await this.server.listen({ port: 9999 })
Expand Down
103 changes: 103 additions & 0 deletions tests/unit/router/RouteTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,60 @@ export default class RouteTest {
assert.deepEqual(response.json(), { id: 10, limit: 2 })
}

@Test()
public async shouldExposeParsedZodValuesThroughAllRequestAccessors({ assert }: Context) {
Route.post('users/:published', async ctx => {
await ctx.response.send({
body: ctx.request.input('syncProfile'),
bodyFromGetter: ctx.request.body.syncProfile,
header: ctx.request.header('x-with-profile'),
headerFromGetter: ctx.request.headers['x-with-profile'],
param: ctx.request.param('published'),
paramFromGetter: ctx.request.params.published,
query: ctx.request.query('withProfile'),
queryFromGetter: ctx.request.queries.withProfile
})
}).schema({
body: z.object({ syncProfile: z.stringbool() }),
headers: z.object({ 'x-with-profile': z.stringbool() }),
params: z.object({ published: z.stringbool() }),
querystring: z.object({ withProfile: z.stringbool() }),
response: {
200: z.object({
body: z.boolean(),
bodyFromGetter: z.boolean(),
header: z.boolean(),
headerFromGetter: z.boolean(),
param: z.boolean(),
paramFromGetter: z.boolean(),
query: z.boolean(),
queryFromGetter: z.boolean()
})
}
})

Route.register()

const response = await Server.request({
path: '/users/true?withProfile=true',
method: 'post',
headers: { 'x-with-profile': 'false' },
payload: { syncProfile: 'true' }
})

assert.equal(response.statusCode, 200)
assert.deepEqual(response.json(), {
body: true,
bodyFromGetter: true,
header: false,
headerFromGetter: false,
param: true,
paramFromGetter: true,
query: true,
queryFromGetter: true
})
}

@Test()
@Cleanup(() => Config.set('openapi.paths', {}))
public async shouldAutomaticallyApplySchemasFromOpenApiConfig({ assert }: Context) {
Expand Down Expand Up @@ -266,6 +320,55 @@ export default class RouteTest {
assert.deepEqual(response.json(), { id: 10, limit: 2 })
}

@Test()
@Cleanup(() => Config.set('openapi.paths', {}))
public async shouldAutomaticallyExposeParsedOpenApiZodValuesInRequestAccessors({ assert }: Context) {
Config.set('openapi.paths', {
'/users/{published}': {
post: {
body: z.object({ syncProfile: z.stringbool() }),
headers: z.object({ 'x-with-profile': z.stringbool() }),
params: z.object({ published: z.stringbool() }),
querystring: z.object({ withProfile: z.stringbool() }),
response: {
200: z.object({
body: z.boolean(),
header: z.boolean(),
param: z.boolean(),
query: z.boolean()
})
}
}
}
})

Route.post('users/:published', async ctx => {
await ctx.response.send({
body: ctx.request.input('syncProfile'),
header: ctx.request.header('x-with-profile'),
param: ctx.request.param('published'),
query: ctx.request.query('withProfile')
})
})

Route.register()

const response = await Server.request({
path: '/users/true?withProfile=false',
method: 'post',
headers: { 'x-with-profile': 'true' },
payload: { syncProfile: 'false' }
})

assert.equal(response.statusCode, 200)
assert.deepEqual(response.json(), {
body: false,
header: true,
param: true,
query: false
})
}

@Test()
public async shouldBeAbleToHideARouteFromTheSwaggerDocumentation({ assert }: Context) {
Route.get('test', new HelloController().index)
Expand Down
Loading