From dcc7a905150dfc751901bc2f8b189e5c1a3bcde7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9B=90=EB=8D=94?= Date: Mon, 4 Jan 2021 22:11:13 +0900 Subject: [PATCH] feat: added response wrapper util --- utils/ResponseWrapper.ts | 21 +++++++++++++++++++++ utils/index.ts | 3 +++ 2 files changed, 24 insertions(+) create mode 100644 utils/ResponseWrapper.ts create mode 100644 utils/index.ts diff --git a/utils/ResponseWrapper.ts b/utils/ResponseWrapper.ts new file mode 100644 index 0000000..10f5fb1 --- /dev/null +++ b/utils/ResponseWrapper.ts @@ -0,0 +1,21 @@ +import http from 'http' +import { NextApiResponse } from 'next' +export default function ResponseWrapper(res: NextApiResponse, { code, message, version=2, data, errors }:ResponseProps) { + if(!code) throw new Error('`code` is required.') + if(!http.STATUS_CODES[code]) throw new Error('Invalid http code.') + res.statusCode = code + + return { code, message: message || http.STATUS_CODES[code], data, errors, version } +} + +interface ResponseProps { + code: number + message?: string + version?: number + data?: Data + errors?: string[] +} + +interface Data { + [key: string]: unknown +} diff --git a/utils/index.ts b/utils/index.ts new file mode 100644 index 0000000..5667084 --- /dev/null +++ b/utils/index.ts @@ -0,0 +1,3 @@ +import ResponseWrapper from './ResponseWrapper' + +export { ResponseWrapper } \ No newline at end of file