Files
template-showcase/src/features/create-note/api/actions.ts
T

29 lines
1.3 KiB
TypeScript

'use server'
import { revalidatePath } from 'next/cache'
import { noteInput, noteRepository } from '@/entities/note'
import { audit, db, logger, serverErrors } from '@/shared/api'
import { indexNote, publishNoteCreated } from '@/shared/lib/optional'
import { ensureVisitor } from '@/shared/lib/visitor-session'
/** Parse, write, audit, revalidate (plan §4.4): the shape every mutation follows. */
export async function createNote(form: FormData): Promise<void> {
try {
const input = noteInput.parse({ title: form.get('title'), body: form.get('body') ?? '' })
const actor = await ensureVisitor()
const note = await noteRepository(db()).create({ ...input, authorId: actor })
await audit().log('note.created', { actor: { kind: 'human', id: actor }, target: { id: note.id } })
logger()?.info('note.created', { 'note.id': note.id, outcome: 'ok' })
// Optional modules: NATS hears of the note and Qdrant indexes it when linked. A failure is
// reported, not raised: the note is saved.
await Promise.all([
publishNoteCreated({ id: note.id, title: note.title }),
indexNote({ id: note.id, title: note.title, body: note.body }),
]).catch((error: unknown) => serverErrors().captureException(error))
revalidatePath('/')
} catch (error) {
logger()?.recordException(error, { 'conusai.action': 'note.created' })
throw error
}
}