From 7eff77ccc470c0640e5fd9f176025d6dbd0babed Mon Sep 17 00:00:00 2001 From: Nguyen Thanh Quang Date: Sun, 28 Nov 2021 06:00:18 +0700 Subject: [PATCH] refactor(api): cors duplication (#109) * refactor(api): cors duplication * refactor(middleware): moved content-type setter to top --- src/lib/middleware/withZipline.ts | 25 +++++-------------------- 1 file changed, 5 insertions(+), 20 deletions(-) diff --git a/src/lib/middleware/withZipline.ts b/src/lib/middleware/withZipline.ts index a277221..4889be1 100644 --- a/src/lib/middleware/withZipline.ts +++ b/src/lib/middleware/withZipline.ts @@ -48,12 +48,11 @@ export type NextApiRes = NextApiResponse & { // } export const withZipline = (handler: (req: NextApiRequest, res: NextApiResponse) => unknown) => (req: NextApiReq, res: NextApiRes) => { + res.setHeader('Content-Type', 'application/json'); + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Content-Allow-Methods', 'GET,HEAD,POST,OPTIONS'); + res.setHeader('Access-Control-Max-Age', '86400'); res.error = (message: string) => { - res.setHeader('Content-Type', 'application/json'); - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Content-Allow-Methods', 'GET,HEAD,POST,OPTIONS'); - res.setHeader('Access-Control-Max-Age', '86400'); - res.json({ error: message, }); @@ -61,10 +60,6 @@ export const withZipline = (handler: (req: NextApiRequest, res: NextApiResponse) res.forbid = (message: string) => { res.setHeader('Content-Type', 'application/json'); - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Content-Allow-Methods', 'GET,HEAD,POST,OPTIONS'); - res.setHeader('Access-Control-Max-Age', '86400'); - res.status(403); res.json({ error: '403: ' + message, @@ -72,11 +67,6 @@ export const withZipline = (handler: (req: NextApiRequest, res: NextApiResponse) }; res.bad = (message: string) => { - res.setHeader('Content-Type', 'application/json'); - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Content-Allow-Methods', 'GET,HEAD,POST,OPTIONS'); - res.setHeader('Access-Control-Max-Age', '86400'); - res.status(401); res.json({ error: '403: ' + message, @@ -84,11 +74,6 @@ export const withZipline = (handler: (req: NextApiRequest, res: NextApiResponse) }; res.json = (json: any) => { - res.setHeader('Content-Type', 'application/json'); - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Content-Allow-Methods', 'GET,HEAD,POST,OPTIONS'); - res.setHeader('Access-Control-Max-Age', '86400'); - res.end(JSON.stringify(json)); }; @@ -158,4 +143,4 @@ export const setCookie = ( const signed = sign64(String(value), config.core.secret); res.setHeader('Set-Cookie', serialize(name, signed, options)); -}; \ No newline at end of file +};