Skip to content

Commit c666d13

Browse files
committed
impr: parse response from discord api with zod
!nuf
1 parent e8c0fc0 commit c666d13

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

backend/src/utils/discord.ts

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,38 +3,33 @@ import { isDevEnvironment } from "./misc";
33
import * as RedisClient from "../init/redis";
44
import { randomBytes } from "crypto";
55
import MonkeyError from "./error";
6+
import { z } from "zod";
7+
import { parseWithSchema as parseJsonWithSchema } from "@monkeytype/util/json";
68

79
const BASE_URL = "https://discord.com/api";
810

9-
type DiscordUser = {
10-
id: string;
11-
username: string;
12-
discriminator: string;
13-
avatar?: string;
14-
bot?: boolean;
15-
system?: boolean;
16-
mfa_enabled?: boolean;
17-
banner?: string;
18-
accent_color?: number;
19-
locale?: string;
20-
verified?: boolean;
21-
email?: string;
22-
flags?: number;
23-
premium_type?: number;
24-
public_flags?: number;
25-
};
11+
const DiscordIdAndAvatarSchema = z.object({
12+
id: z.string(),
13+
avatar: z.string().optional(),
14+
});
15+
type DiscordIdAndAvatar = z.infer<typeof DiscordIdAndAvatarSchema>;
2616

2717
export async function getDiscordUser(
2818
tokenType: string,
2919
accessToken: string
30-
): Promise<DiscordUser> {
20+
): Promise<DiscordIdAndAvatar> {
3121
const response = await fetch(`${BASE_URL}/users/@me`, {
3222
headers: {
3323
authorization: `${tokenType} ${accessToken}`,
3424
},
3525
});
3626

37-
return (await response.json()) as DiscordUser;
27+
const parsed = parseJsonWithSchema(
28+
await response.text(),
29+
DiscordIdAndAvatarSchema
30+
);
31+
32+
return parsed;
3833
}
3934

4035
export async function getOauthLink(uid: string): Promise<string> {

0 commit comments

Comments
 (0)