api/src/routes/private/discord.ts
71 lines · 2353 bytes
1// Discord invite info, projected to a compact response shape
2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch'
4import { freshSeconds } from '@/lib/cache/freshness'
5import { newApp } from '@/lib/openapi'
6import { DiscordInviteSchema, ErrorResponse, Ok } from '@/schemas'
7
8const app = newApp()
9
10const FRESH_TTL = freshSeconds('discord')
11
12interface Invite {
13 code?: string
14 guild?: { id?: string; name?: string; icon?: string; splash?: string }
15 channel?: { name?: string }
16 inviter?: { global_name?: string }
17 approximate_member_count?: number
18 approximate_presence_count?: number
19}
20
21const iconUrl = (guildId?: string, icon?: string) =>
22 guildId && icon ? `https://cdn.discordapp.com/icons/${guildId}/${icon}.webp` : null
23
24const bannerUrl = (guildId?: string, splash?: string) =>
25 guildId && splash
26 ? `https://cdn.discordapp.com/splashes/${guildId}/${splash}.webp?size=1024`
27 : null
28
29const route = createRoute({
30 method: 'get',
31 path: '/enrich/discord/{invite}',
32 tags: ['Enrichment'],
33 summary: 'Discord server info',
34 request: { params: z.object({ invite: z.string().min(4) }) },
35 responses: {
36 200: Ok(DiscordInviteSchema),
37 400: ErrorResponse,
38 401: ErrorResponse,
39 500: ErrorResponse,
40 502: ErrorResponse,
41 },
42})
43
44// Hit Discord invite endpoint, return the small fields the site needs
45app.openapi(route, async (c) => {
46 const { invite } = c.req.valid('param')
47 const headers: Record<string, string> = {}
48 if (c.env.DISCORD_BOT_TOKEN) {
49 headers.Authorization = `Bot ${c.env.DISCORD_BOT_TOKEN}`
50 }
51 const upstream =
52 `https://discord.com/api/v9/invites/${encodeURIComponent(invite)}` +
53 '?with_counts=true&with_expiration=true'
54 const data = await c.var.storage.fetch(`discord:${invite}`, FRESH_TTL, async () => {
55 const raw = await fetchJson<Invite>(upstream, { headers })
56 const guild = raw.guild
57 return {
58 inviteCode: raw.code ?? null,
59 name: guild?.name ?? null,
60 memberCount: raw.approximate_member_count ?? null,
61 memberOnlineCount: raw.approximate_presence_count ?? null,
62 channel: raw.channel?.name ?? null,
63 icon: iconUrl(guild?.id, guild?.icon),
64 banner: bannerUrl(guild?.id, guild?.splash),
65 inviter: raw.inviter?.global_name ?? null,
66 }
67 })
68 return c.json(data, 200)
69})
70
71export default app