-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.ts
55 lines (44 loc) · 1.44 KB
/
plugin.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
50
51
52
53
54
55
import { type FastifyPluginCallback } from "fastify";
import { IronSession, SessionOptions, getIronSession } from "iron-session";
import fp from "fastify-plugin";
export { type IronSession } from "iron-session";
export interface SessionData {
[key: string]: any;
}
declare module "fastify" {
interface FastifyRequest {
session: () => Promise<IronSession<SessionData>>;
}
}
type IronSessionPluginOptions = SessionOptions & {
sessionName?: string;
};
const plugin: FastifyPluginCallback<
IronSessionPluginOptions | IronSessionPluginOptions[]
> = (fastify, opts, done) => {
const sessionNames = new Map<string, IronSessionPluginOptions>();
if (Array.isArray(opts)) {
for (const opt of opts) {
const sessionName = opt.sessionName || "session";
sessionNames.set(sessionName, opt);
fastify.decorateRequest(sessionName, () => null);
}
} else {
const sessionName = opts.sessionName || "session";
sessionNames.set(sessionName, opts);
fastify.decorateRequest(sessionName, () => null);
}
fastify.addHook("onRequest", async (request, reply) => {
for (const [sessionName, opts] of sessionNames) {
// @ts-ignore, end user should be able to create a custom session name and override in declaration
request[sessionName] = async () => {
return getIronSession(request.raw, reply.raw, opts);
};
}
});
done();
};
export default fp(plugin, {
fastify: "4.x",
name: "iron-session",
});