Barazo AppView backend barazo.forum
at main 60 lines 1.9 kB view raw
1import { 2 topicPostSchema, 3 topicReplySchema, 4 reactionSchema, 5 voteSchema, 6 type TopicPostInput, 7 type TopicReplyInput, 8 type ReactionInput, 9 type VoteInput, 10} from '@singi-labs/barazo-lexicons' 11import type { SupportedCollection } from './types.js' 12import { isSupportedCollection } from './types.js' 13 14const MAX_RECORD_SIZE = 64 * 1024 // 64KB 15 16/** Maps collection NSIDs to their validated Zod output type. */ 17export type CollectionDataMap = { 18 'forum.barazo.topic.post': TopicPostInput 19 'forum.barazo.topic.reply': TopicReplyInput 20 'forum.barazo.interaction.reaction': ReactionInput 21 'forum.barazo.interaction.vote': VoteInput 22} 23 24type ValidationResult<T = unknown> = { success: true; data: T } | { success: false; error: string } 25 26const schemaMap: Record< 27 SupportedCollection, 28 { safeParse: (data: unknown) => { success: boolean; data?: unknown; error?: unknown } } 29> = { 30 'forum.barazo.topic.post': topicPostSchema, 31 'forum.barazo.topic.reply': topicReplySchema, 32 'forum.barazo.interaction.reaction': reactionSchema, 33 'forum.barazo.interaction.vote': voteSchema, 34} 35 36export function validateRecord<C extends SupportedCollection>( 37 collection: C, 38 record: unknown 39): ValidationResult<CollectionDataMap[C]> { 40 if (!isSupportedCollection(collection)) { 41 return { success: false, error: `Unsupported collection: ${String(collection)}` } 42 } 43 44 // Size check: rough estimate using JSON serialization 45 const serialized = JSON.stringify(record) 46 if (serialized.length > MAX_RECORD_SIZE) { 47 return { 48 success: false, 49 error: `Record exceeds maximum size of ${String(MAX_RECORD_SIZE)} bytes`, 50 } 51 } 52 53 const schema = schemaMap[collection] 54 const result = schema.safeParse(record) 55 if (!result.success) { 56 return { success: false, error: `Validation failed for ${collection}` } 57 } 58 59 return { success: true, data: result.data as CollectionDataMap[C] } 60}