forked from vvo/iron-session
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
87 lines (77 loc) · 2.61 KB
/
Copy pathindex.ts
File metadata and controls
87 lines (77 loc) · 2.61 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import type {
NextApiHandler,
GetServerSidePropsContext,
GetServerSidePropsResult,
NextApiRequest,
NextApiResponse,
} from "next";
import type { IronSessionOptions } from "iron-session";
import { getIronSession } from "iron-session";
import getPropertyDescriptorForReqSession from "../src/getPropertyDescriptorForReqSession";
import { IncomingMessage, ServerResponse } from "http";
// Argument types based on getIronSession function
type GetIronSessionApiOptions = (
request: NextApiRequest,
response: NextApiResponse,
) => Promise<IronSessionOptions> | IronSessionOptions;
export function withIronSessionApiRoute(
handler: NextApiHandler,
options: IronSessionOptions | GetIronSessionApiOptions,
): NextApiHandler {
return async function nextApiHandlerWrappedWithIronSession(req, res) {
let sessionOptions: IronSessionOptions;
// If options is a function, call it and assign the results back.
if (options instanceof Function) {
sessionOptions = await options(req, res);
} else {
sessionOptions = options;
}
const session = await getIronSession(req, res, sessionOptions);
// 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);
};
}
// Argument type based on the SSR context
type GetIronSessionSSROptions = (
request: IncomingMessage,
response: ServerResponse,
) => Promise<IronSessionOptions> | IronSessionOptions;
export function withIronSessionSsr<
P extends { [key: string]: unknown } = { [key: string]: unknown },
>(
handler: (
context: GetServerSidePropsContext,
) => GetServerSidePropsResult<P> | Promise<GetServerSidePropsResult<P>>,
options: IronSessionOptions | GetIronSessionSSROptions,
) {
return async function nextGetServerSidePropsHandlerWrappedWithIronSession(
context: GetServerSidePropsContext,
) {
let sessionOptions: IronSessionOptions;
// If options is a function, call it and assign the results back.
if (options instanceof Function) {
sessionOptions = await options(context.req, context.res);
} else {
sessionOptions = options;
}
const session = await getIronSession(
context.req,
context.res,
sessionOptions,
);
Object.defineProperty(
context.req,
"session",
getPropertyDescriptorForReqSession(session),
);
return handler(context);
};
}