core/utils/ResponseWrapper.ts
SKINMAKER b421d1ab64
chore: apply prettier (#637)
* chore: apply prettier

* chore: edit ready comment

* chore: move ts comment
2023-11-29 22:04:33 +09:00

26 lines
754 B
TypeScript

import http from 'http'
import { ResponseProps } from '@types'
import { ErrorText } from './Constants'
export default function ResponseWrapper<T = unknown>(
res: ApiResponse,
{ code = 200, message, version = 2, data, errors }: ResponseProps<T>
) {
if (!code) throw new Error('`code` is required.')
if (!http.STATUS_CODES[code]) throw new Error('Invalid http code.')
res.setHeader('Access-Control-Allow-Origin', process.env.KOREANBOTS_URL)
res.status(code)
res.json({
code,
data,
errors,
version,
...(message || !data ? { message: message || ErrorText[code] || http.STATUS_CODES[code] } : {}),
})
}
interface ApiResponse {
status(status: string | number): void
setHeader(key: string, value: string): void
json(json: unknown): void
}