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.
 
 

59 lines
1.5 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 BLANK_BODY_STATUS_CODES = [
  10. constants.HTTP_STATUS_NO_CONTENT,
  11. constants.HTTP_STATUS_RESET_CONTENT,
  12. ]
  13. const fastifySendData = async (app: FastifyInstance) => {
  14. const sendDataKey = 'sendData' as const
  15. app.decorateReply(sendDataKey, function reply<T extends ResponseDataInterface>(this: FastifyReply, data: T) {
  16. this.status(data.statusCode)
  17. if (data.statusMessage) {
  18. this.raw.statusMessage = data.statusMessage
  19. }
  20. if (!BLANK_BODY_STATUS_CODES.includes(data.statusCode)) {
  21. this.send(data.body)
  22. return
  23. }
  24. this.removeHeader('content-type')
  25. this.removeHeader('content-length')
  26. this.send()
  27. })
  28. }
  29. type SendData<O extends unknown = unknown, T extends ResponseDataInterface<O> = ResponseDataInterface<O>> = (data: T) => void
  30. declare module 'fastify' {
  31. interface FastifyReply {
  32. sendData: SendData
  33. }
  34. }
  35. export const HttpResponse = <T extends unknown = undefined>(
  36. statusCode = constants.HTTP_STATUS_OK,
  37. statusMessage?: string,
  38. ) => class HttpResponseData {
  39. readonly statusCode = statusCode
  40. readonly statusMessage = statusMessage
  41. readonly body?: { data: T }
  42. constructor(data?: T) {
  43. if (data && !BLANK_BODY_STATUS_CODES.includes(statusCode)) {
  44. this.body = {
  45. data,
  46. }
  47. }
  48. }
  49. }
  50. export default fp(fastifySendData)