fix: detect Express/Fastify requests correctly as of Fastify v4.19.0 (#672)

This commit is contained in:
Brenden Palmer 2023-07-17 02:19:03 -04:00 committed by GitHub
parent d328e343a4
commit 8be8475fa6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 5 deletions

View File

@ -41,6 +41,7 @@ function fastifyContextFactory(query: FastifyRequest['query']): Partial<Executio
protocol: 'http',
hostname: 'localhost',
url: '/items?search=2423',
originalUrl: '/items?search=2423',
query: query,
}),
}),

View File

@ -1,7 +1,16 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common'
import { Request } from 'express'
import type { Request as ExpressRequest } from 'express'
import type { FastifyRequest } from 'fastify'
import { pickBy, Dictionary, isString, mapKeys } from 'lodash'
function isRecord(data: unknown): data is Record<string, unknown> {
return data !== null && typeof data === 'object' && !Array.isArray(data)
}
function isExpressRequest(request: unknown): request is ExpressRequest {
return isRecord(request) && typeof request.get === 'function'
}
export interface PaginateQuery {
page?: number
limit?: number
@ -41,12 +50,12 @@ function parseParam<T>(queryParam: unknown, parserLogic: (param: string, res: an
}
export const Paginate = createParamDecorator((_data: unknown, ctx: ExecutionContext): PaginateQuery => {
const request: Request = ctx.switchToHttp().getRequest()
const { query } = request
const request: ExpressRequest | FastifyRequest = ctx.switchToHttp().getRequest()
const query = request.query as Record<string, unknown>
// Determine if Express or Fastify to rebuild the original url and reduce down to protocol, host and base url
let originalUrl: any
if (request.originalUrl) {
let originalUrl: string
if (isExpressRequest(request)) {
originalUrl = request.protocol + '://' + request.get('host') + request.originalUrl
} else {
originalUrl = request.protocol + '://' + request.hostname + request.url