(
request: Request,
schema?: any,
options?: { skipAuth: boolean },
)
| 10 | import { getWebsiteSegment } from '@/queries/prisma'; |
| 11 | |
| 12 | export async function parseRequest( |
| 13 | request: Request, |
| 14 | schema?: any, |
| 15 | options?: { skipAuth: boolean }, |
| 16 | ): Promise<any> { |
| 17 | const url = new URL(request.url); |
| 18 | let query = Object.fromEntries(url.searchParams); |
| 19 | let body = await getJsonBody(request); |
| 20 | let error: () => undefined | undefined | Response; |
| 21 | let auth = null; |
| 22 | |
| 23 | if (schema) { |
| 24 | const isGet = request.method === 'GET'; |
| 25 | const rawQuery = query; |
| 26 | const result = schema.safeParse(isGet ? query : body); |
| 27 | |
| 28 | if (!result.success) { |
| 29 | error = () => badRequest(z.treeifyError(result.error)); |
| 30 | } else if (isGet) { |
| 31 | query = result.data; |
| 32 | |
| 33 | // Re-add dynamic params stripped by Zod schema: suffixed filter params (browser1, os2) |
| 34 | for (const key of Object.keys(rawQuery)) { |
| 35 | if ((/\d+$/.test(key) || /^pf_/.test(key)) && !(key in query)) { |
| 36 | query[key] = rawQuery[key]; |
| 37 | } |
| 38 | } |
| 39 | } else { |
| 40 | body = result.data; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | if (!options?.skipAuth && !error) { |
| 45 | auth = await checkAuth(request); |
| 46 | |
| 47 | if (!auth) { |
| 48 | error = () => unauthorized(); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | return { url, query, body, auth, error }; |
| 53 | } |
| 54 | |
| 55 | export async function getJsonBody(request: Request) { |
| 56 | try { |
no test coverage detected