Web API for code.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

54 lines
1.4 KiB

  1. import { FastifyInstance, FastifyReply } from 'fastify'
  2. import fp from 'fastify-plugin'
  3. import { constants } from 'http2'
  4. export interface ResponseDataInterface<T extends unknown = undefined> {
  5. statusCode: number
  6. statusMessage?: string
  7. body?: T extends undefined ? undefined : { data: T }
  8. }
  9. const fastifySendData = async (app: FastifyInstance) => {
  10. const sendDataKey = 'sendData' as const
  11. app.decorateReply(sendDataKey, function reply<T extends ResponseDataInterface>(this: FastifyReply, data: T) {
  12. this.status(data.statusCode)
  13. if (data.statusMessage) {
  14. this.raw.statusMessage = data.statusMessage
  15. }
  16. if (data.statusCode !== constants.HTTP_STATUS_NO_CONTENT) {
  17. this.send(data.body)
  18. return
  19. }
  20. this.removeHeader('content-type')
  21. this.removeHeader('content-length')
  22. this.send()
  23. })
  24. }
  25. type SendData<O extends unknown = unknown, T extends ResponseDataInterface<O> = ResponseDataInterface<O>> = (data: T) => void
  26. declare module 'fastify' {
  27. interface FastifyReply {
  28. sendData: SendData
  29. }
  30. }
  31. export const HttpResponse = <T extends unknown = undefined>(
  32. statusCode = constants.HTTP_STATUS_OK,
  33. statusMessage?: string,
  34. ) => class HttpResponseData {
  35. readonly statusCode = statusCode
  36. readonly statusMessage = statusMessage
  37. readonly body?: { data: T }
  38. constructor(data?: T) {
  39. if (data && statusCode !== constants.HTTP_STATUS_NO_CONTENT) {
  40. this.body = {
  41. data,
  42. }
  43. }
  44. }
  45. }
  46. export default fp(fastifySendData)