|
| 1 | +import { Effect, Exit } from 'effect'; |
| 2 | +import type { SpaceEvent } from 'graph-framework-space-events'; |
| 3 | +import { applyEvent } from 'graph-framework-space-events'; |
| 4 | +import { prisma } from '../prisma.js'; |
| 5 | + |
| 6 | +type Params = { |
| 7 | + accountId: string; |
| 8 | + spaceId: string; |
| 9 | + event: SpaceEvent; |
| 10 | +}; |
| 11 | + |
| 12 | +export async function applySpaceEvent({ accountId, spaceId, event }: Params) { |
| 13 | + return await prisma.$transaction(async (transaction) => { |
| 14 | + if (event.transaction.type === 'create-space') { |
| 15 | + throw new Error('applySpaceEvent does not support create-space events.'); |
| 16 | + } |
| 17 | + |
| 18 | + // verify that the account is a member of the space |
| 19 | + // TODO verify that the account is a admin of the space |
| 20 | + await transaction.space.findUniqueOrThrow({ |
| 21 | + where: { id: spaceId, members: { some: { id: accountId } } }, |
| 22 | + }); |
| 23 | + |
| 24 | + const lastEvent = await transaction.spaceEvent.findFirstOrThrow({ |
| 25 | + where: { spaceId }, |
| 26 | + orderBy: { counter: 'desc' }, |
| 27 | + }); |
| 28 | + |
| 29 | + const result = await Effect.runPromiseExit(applyEvent({ event })); |
| 30 | + if (Exit.isFailure(result)) { |
| 31 | + throw new Error('Invalid event'); |
| 32 | + } |
| 33 | + |
| 34 | + return await transaction.spaceEvent.create({ |
| 35 | + data: { |
| 36 | + spaceId, |
| 37 | + counter: lastEvent.counter + 1, |
| 38 | + event: JSON.stringify(event), |
| 39 | + id: event.transaction.id, |
| 40 | + state: JSON.stringify(result.value), |
| 41 | + }, |
| 42 | + }); |
| 43 | + }); |
| 44 | +} |
0 commit comments