-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcurrentUser.ts
60 lines (51 loc) · 1.6 KB
/
currentUser.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
57
58
59
60
import { z } from "zod";
import { fetchCurrentUser } from "@thunderstore/thunderstore-api";
import { DapperTsInterface } from "../index";
import { formatErrorMessage } from "../utils";
const oAuthConnectionSchema = z.object({
provider: z.string().nonempty(),
username: z.string().nonempty(),
avatar: z.string().nullable(),
});
const teamSchema = z.object({
name: z.string().nonempty(),
role: z.union([z.literal("owner"), z.literal("member")]),
member_count: z.number().int().gte(1),
});
const schema = z.object({
username: z.string().nonempty(),
capabilities: z.string().array(),
connections: oAuthConnectionSchema.array(),
rated_packages: z.string().array(),
rated_packages_cyberstorm: z.string().array(),
subscription: z.object({
expires: z.string().datetime().nullable(),
}),
teams_full: teamSchema.array(),
});
export async function getCurrentUser(this: DapperTsInterface) {
if (this.config.sessionId === undefined) {
return {
username: null,
capabilities: [],
connections: [],
rated_packages: [],
rated_packages_cyberstorm: [],
subscription: { expires: null },
teams: [],
};
}
const data = await fetchCurrentUser(this.config);
const parsed = schema.safeParse(data);
if (!parsed.success) {
throw new Error(formatErrorMessage(parsed.error));
}
// For legacy support, the backend returns teams in two formats.
// Clients don't need to know about the old one, so replace it with
// the new one.
const { teams_full, ...currentUser } = {
...parsed.data,
teams: parsed.data.teams_full,
};
return currentUser;
}