Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: server/api-utils.ts #21148

Merged
merged 18 commits into from
Jan 26, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions packages/next/next-server/server/api-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export async function apiResolver(
apiContext: __ApiPreviewProps,
propagateError: boolean,
onError?: ({ err }: { err: any }) => Promise<void>
) {
): Promise<void> {
const apiReq = req as NextApiRequest
const apiRes = res as NextApiResponse

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -362,29 +364,24 @@ export function tryGetPreviewData(
}
}

function isNotValidData(str: string): boolean {
return typeof str !== 'string' || str.length < 16
}

function setPreviewData<T>(
res: NextApiResponse<T>,
data: object | string, // TODO: strict runtime type checking
options: {
maxAge?: number
} & __ApiPreviewProps
): NextApiResponse<T> {
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')
}

Expand Down