|
- import { FastifyInstance, FastifyReply } from 'fastify'
- import fp from 'fastify-plugin'
- import { constants } from 'http2'
-
- export interface ResponseDataInterface<T extends unknown = undefined> {
- statusCode: number
- statusMessage?: string
- body?: T extends undefined ? undefined : { data: T }
- }
-
- const fastifySendData = async (app: FastifyInstance) => {
- const sendDataKey = 'sendData' as const
- app.decorateReply(sendDataKey, function reply<T extends ResponseDataInterface>(this: FastifyReply, data: T) {
- this.status(data.statusCode)
- if (data.statusMessage) {
- this.raw.statusMessage = data.statusMessage
- }
- if (data.statusCode !== constants.HTTP_STATUS_NO_CONTENT) {
- this.send(data.body)
- return
- }
- this.removeHeader('content-type')
- this.removeHeader('content-length')
- this.send()
- })
- }
-
- type SendData<O extends unknown = unknown, T extends ResponseDataInterface<O> = ResponseDataInterface<O>> = (data: T) => void
-
- declare module 'fastify' {
- interface FastifyReply {
- sendData: SendData
- }
- }
-
- export const HttpResponse = <T extends unknown = undefined>(
- statusCode = constants.HTTP_STATUS_OK,
- statusMessage?: string,
- ) => class HttpResponseData {
- readonly statusCode = statusCode
- readonly statusMessage = statusMessage
- readonly body?: { data: T }
-
- constructor(data?: T) {
- if (data && statusCode !== constants.HTTP_STATUS_NO_CONTENT) {
- this.body = {
- data,
- }
- }
- }
- }
-
- export default fp(fastifySendData)
|