|
| 1 | +import { BOTS } from '@chatsift/backend-core'; |
| 2 | +import { internal } from '@hapi/boom'; |
| 3 | +import type { NextHandler, Response } from 'polka'; |
| 4 | +import z from 'zod'; |
| 5 | +import { context } from '../../context.js'; |
| 6 | +import { isAuthed } from '../../middleware/isAuthed.js'; |
| 7 | +import { fetchGuildChannels, type GuildChannelInfo } from '../../util/channels.js'; |
| 8 | +import { APIMapping } from '../../util/discordAPI.js'; |
| 9 | +import { fetchMe } from '../../util/me.js'; |
| 10 | +import type { TRequest } from '../route.js'; |
| 11 | +import { Route, RouteMethod } from '../route.js'; |
| 12 | + |
| 13 | +export type { GuildChannelInfo } from '../../util/channels.js'; |
| 14 | + |
| 15 | +const querySchema = z.strictObject({ |
| 16 | + for_bot: z.enum(BOTS), |
| 17 | + force_fresh: z.stringbool().optional().default(false), |
| 18 | +}); |
| 19 | +export type GetGuildQuery = z.input<typeof querySchema>; |
| 20 | + |
| 21 | +export interface GetGuildResult { |
| 22 | + channels: GuildChannelInfo[]; |
| 23 | +} |
| 24 | + |
| 25 | +export default class GetGuild extends Route<GetGuildResult, typeof querySchema> { |
| 26 | + public readonly info = { |
| 27 | + method: RouteMethod.get, |
| 28 | + path: '/v3/guilds/:guildId', |
| 29 | + } as const; |
| 30 | + |
| 31 | + public override readonly queryValidationSchema = querySchema; |
| 32 | + |
| 33 | + public override readonly middleware = [ |
| 34 | + ...isAuthed({ fallthrough: false, isGlobalAdmin: false, isGuildManager: true }), |
| 35 | + ]; |
| 36 | + |
| 37 | + public override async handle(req: TRequest<typeof querySchema>, res: Response, next: NextHandler) { |
| 38 | + const { guildId } = req.params as { guildId: string }; |
| 39 | + const { force_fresh, for_bot } = req.query; |
| 40 | + |
| 41 | + const me = await fetchMe(req.tokens!.access.discordAccessToken, force_fresh); |
| 42 | + const guild = me.guilds.find((g) => g.id === guildId); |
| 43 | + if (!guild) { |
| 44 | + // Should be impossible because of the auth checks |
| 45 | + context.logger.error({ guildId, userId: me.id }, 'guild not found for user in auth-gated route'); |
| 46 | + return next(internal()); |
| 47 | + } |
| 48 | + |
| 49 | + const channels = await fetchGuildChannels(guild, APIMapping[for_bot], force_fresh); |
| 50 | + const result: GetGuildResult = { |
| 51 | + channels, |
| 52 | + }; |
| 53 | + |
| 54 | + res.statusCode = 200; |
| 55 | + res.setHeader('Content-Type', 'application/json'); |
| 56 | + return res.end(JSON.stringify(result)); |
| 57 | + } |
| 58 | +} |
0 commit comments