sendMessage.ts 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. import { brivenError, mutation, type Ctx } from '@briven/cli/server';
  2. import { ulid } from '@briven/shared';
  3. interface Args {
  4. roomId: string;
  5. authorName: string;
  6. body: string;
  7. }
  8. export default mutation(async (ctx: Ctx, args: Args) => {
  9. if (!args.roomId)
  10. throw new brivenError('validation_failed', 'roomId is required', { status: 400 });
  11. const author = args.authorName?.trim();
  12. const body = args.body?.trim();
  13. if (!author)
  14. throw new brivenError('validation_failed', 'authorName is required', { status: 400 });
  15. if (!body) throw new brivenError('validation_failed', 'body is required', { status: 400 });
  16. if (body.length > 2000)
  17. throw new brivenError('validation_failed', 'body too long (max 2000 chars)', { status: 400 });
  18. const [room] = await ctx.db('rooms').select(['id']).where({ id: args.roomId }).limit(1);
  19. if (!room)
  20. throw new brivenError('not_found', `no room ${args.roomId}`, { status: 404 });
  21. const id = ulid('msg');
  22. const [row] = await ctx
  23. .db('messages')
  24. .insert({ id, roomId: args.roomId, authorName: author, body })
  25. .returning();
  26. return row;
  27. });