Barazo AppView backend
barazo.forum
1import type { FastifyInstance, FastifyRequest } from 'fastify'
2import { badRequest } from '../lib/api-errors.js'
3
4declare module 'fastify' {
5 interface FastifyRequest {
6 communityDid: string | undefined
7 }
8}
9
10export interface CommunityResolver {
11 resolve(hostname: string): Promise<string | undefined>
12}
13
14/**
15 * Extract communityDid from request, throwing 400 if not set.
16 * Use in route handlers that require a community context (most write operations).
17 */
18export function requireCommunityDid(request: FastifyRequest): string {
19 const { communityDid } = request
20 if (!communityDid) {
21 throw badRequest('Community context required')
22 }
23 return communityDid
24}
25
26export function createSingleResolver(communityDid: string): CommunityResolver {
27 return { resolve: () => Promise.resolve(communityDid) }
28}
29
30export function registerCommunityResolver(
31 app: FastifyInstance,
32 resolver: CommunityResolver,
33 mode: 'single' | 'multi'
34): void {
35 app.decorateRequest('communityDid', undefined as string | undefined)
36
37 app.addHook('onRequest', async (request, reply) => {
38 const communityDid = await resolver.resolve(request.hostname)
39 if (!communityDid && mode === 'single') {
40 return reply.status(404).send({ error: 'Community not found' })
41 }
42 request.communityDid = communityDid
43 })
44}