From c110e45b62d301cd4cfc38b8ced19275082427ef Mon Sep 17 00:00:00 2001 From: tarunama Date: Tue, 26 Jan 2021 18:52:00 +0900 Subject: [PATCH] refactor: server/api-utils.ts (#21148) - Add return type to function - Add [isNotValidData](https://github.com/vercel/next.js/pull/21148/files#diff-64466461287cc1a70ce5597e3e1d18ac22755f9aeb7ff1865160a8c057540983R374) function for readability --- packages/next/next-server/server/api-utils.ts | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/packages/next/next-server/server/api-utils.ts b/packages/next/next-server/server/api-utils.ts index f04176eb33d96b4..e318de716a51288 100644 --- a/packages/next/next-server/server/api-utils.ts +++ b/packages/next/next-server/server/api-utils.ts @@ -28,7 +28,7 @@ export async function apiResolver( apiContext: __ApiPreviewProps, propagateError: boolean, onError?: ({ err }: { err: any }) => Promise -) { +): Promise { const apiReq = req as NextApiRequest const apiRes = res as NextApiResponse @@ -166,7 +166,9 @@ function parseJson(str: string): object { * Parse cookies from `req` header * @param req request object */ -export function getCookieParser(req: IncomingMessage) { +export function getCookieParser( + req: IncomingMessage +): () => NextApiRequestCookies { return function parseCookie(): NextApiRequestCookies { const header: undefined | string | string[] = req.headers.cookie @@ -362,6 +364,10 @@ export function tryGetPreviewData( } } +function isNotValidData(str: string): boolean { + return typeof str !== 'string' || str.length < 16 +} + function setPreviewData( res: NextApiResponse, data: object | string, // TODO: strict runtime type checking @@ -369,22 +375,13 @@ function setPreviewData( maxAge?: number } & __ApiPreviewProps ): NextApiResponse { - if ( - typeof options.previewModeId !== 'string' || - options.previewModeId.length < 16 - ) { + if (isNotValidData(options.previewModeId)) { throw new Error('invariant: invalid previewModeId') } - if ( - typeof options.previewModeEncryptionKey !== 'string' || - options.previewModeEncryptionKey.length < 16 - ) { + if (isNotValidData(options.previewModeEncryptionKey)) { throw new Error('invariant: invalid previewModeEncryptionKey') } - if ( - typeof options.previewModeSigningKey !== 'string' || - options.previewModeSigningKey.length < 16 - ) { + if (isNotValidData(options.previewModeSigningKey)) { throw new Error('invariant: invalid previewModeSigningKey') }