-
-
Notifications
You must be signed in to change notification settings - Fork 448
/
load.ts
56 lines (55 loc) · 2.07 KB
/
load.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
56
import type { ServerLoadEvent } from "$lib/kit.js";
import type { AuthServerLoadEvent, Session } from "../types.js";
import type { Context } from "./index.js";
export const handleServerLoadFunction = (context: Context) => {
const handleServerLoad = <
LoadFunctions extends ((
event: AuthServerLoadEvent,
context: Context
) => Promise<Record<string, any>>)[]
>(
...loadFunctions: LoadFunctions
) => {
return async (event: ServerLoadEvent) => {
const getSession = async (): Promise<Session> => {
const accessToken = event.cookies.get("access_token");
const fingerprintToken = event.cookies.get("fingerprint_token");
const refreshToken = event.cookies.get("refresh_token");
if (!accessToken || !fingerprintToken || !refreshToken)
return null;
try {
const user = await context.auth.getUserFromAccessToken(
accessToken,
fingerprintToken
);
return {
user,
access_token: accessToken,
refresh_token: refreshToken,
};
} catch {
return null;
}
};
let parentData: null | Record<string, any> = null;
const parent = async () => {
if (parentData) return parentData;
const data = await event.parent();
parentData = Object.freeze(data);
return data;
};
event.parent = parent;
const returnData = {};
const customLoadEvent = {
...event,
getSession,
};
for (const load of loadFunctions) {
const data = await load(customLoadEvent, context);
Object.assign(returnData, data);
}
return returnData;
};
};
return handleServerLoad;
};