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
|
import type { AniListAuthorisation } from "$lib/Data/AniList/identity";
import { Effect, Result, Schema } from "effect";
const UserCookieSchema = Schema.Struct({
token_type: Schema.String,
expires_in: Schema.Number,
access_token: Schema.String,
refresh_token: Schema.String,
});
export const decodeAuthCookieEffect = (cookie: string) =>
Effect.gen(function* () {
const parsedCookie = yield* Effect.try({
try: () => JSON.parse(cookie) as unknown,
catch: (cause) => new Error("Invalid user cookie JSON", { cause }),
});
const decodedCookie = yield* Effect.try({
try: () => Schema.decodeUnknownSync(UserCookieSchema)(parsedCookie),
catch: (cause) => new Error("Invalid user cookie payload", { cause }),
});
return {
tokenType: decodedCookie.token_type,
expiresIn: decodedCookie.expires_in,
accessToken: decodedCookie.access_token,
refreshToken: decodedCookie.refresh_token,
} as AniListAuthorisation;
});
export const decodeAuthCookieEither = (cookie: string) =>
Result.try({
try: () => Effect.runSync(decodeAuthCookieEffect(cookie)),
catch: (cause) =>
cause instanceof Error
? cause
: new Error("Failed to decode user cookie", { cause }),
});
export const decodeAuthCookieOrThrow = (
cookie: string,
): AniListAuthorisation => {
const decoded = decodeAuthCookieEither(cookie);
return Result.getOrThrow(decoded);
};
|