-
-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathindex.ts
49 lines (46 loc) · 1.54 KB
/
index.ts
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 {
NextApiHandler,
GetServerSidePropsContext,
GetServerSidePropsResult,
} from "next";
import type { IronSessionOptions } from "iron-session";
import { getIronSession } from "iron-session";
import getPropertyDescriptorForReqSession from "../src/getPropertyDescriptorForReqSession";
export function withIronSessionApiRoute(
handler: NextApiHandler,
options: IronSessionOptions,
): NextApiHandler {
return async function nextApiHandlerWrappedWithIronSession(req, res) {
const session = await getIronSession(req, res, options);
// we define req.session as being enumerable (so console.log(req) shows it)
// and we also want to allow people to do:
// req.session = { admin: true }; or req.session = {...req.session, admin: true};
// req.session.save();
Object.defineProperty(
req,
"session",
getPropertyDescriptorForReqSession(session),
);
return handler(req, res);
};
}
export function withIronSessionSsr<
P extends { [key: string]: unknown } = { [key: string]: unknown },
>(
handler: (
context: GetServerSidePropsContext,
) => GetServerSidePropsResult<P> | Promise<GetServerSidePropsResult<P>>,
options: IronSessionOptions,
) {
return async function nextGetServerSidePropsHandlerWrappedWithIronSession(
context: GetServerSidePropsContext,
) {
const session = await getIronSession(context.req, context.res, options);
Object.defineProperty(
context.req,
"session",
getPropertyDescriptorForReqSession(session),
);
return handler(context);
};
}