forked from calcom/cal.com
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuildLegacyCtx.tsx
49 lines (43 loc) · 1.62 KB
/
buildLegacyCtx.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import type { SearchParams } from "app/_types";
import { type Params } from "app/_types";
import type { GetServerSidePropsContext } from "next";
import { type ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
import { type ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies";
const createProxifiedObject = (object: Record<string, string>) =>
new Proxy(object, {
set: () => {
throw new Error("You are trying to modify 'headers' or 'cookies', which is not supported in app dir");
},
});
const buildLegacyHeaders = (headers: ReadonlyHeaders) => {
const headersObject = Object.fromEntries(headers.entries());
return createProxifiedObject(headersObject);
};
const buildLegacyCookies = (cookies: ReadonlyRequestCookies) => {
const cookiesObject = cookies.getAll().reduce<Record<string, string>>((acc, { name, value }) => {
acc[name] = value;
return acc;
}, {});
return createProxifiedObject(cookiesObject);
};
export const buildLegacyCtx = (
headers: ReadonlyHeaders,
cookies: ReadonlyRequestCookies,
params: Params,
searchParams: SearchParams
) => {
return {
query: { ...searchParams, ...params },
params,
req: { headers: buildLegacyHeaders(headers), cookies: buildLegacyCookies(cookies) },
res: new Proxy(Object.create(null), {
// const { req, res } = ctx - valid
// res.anything - throw
get() {
throw new Error(
"You are trying to access the 'res' property of the context, which is not supported in app dir"
);
},
}),
} as unknown as GetServerSidePropsContext;
};