increment.ts 748 B

1234567891011121314151617181920212223
  1. import { mutation, type Ctx } from '@briven/cli/server';
  2. interface Args {
  3. id?: string;
  4. by?: number;
  5. }
  6. /**
  7. * Single-row UPDATE — postgres ON CONFLICT creates the row on first
  8. * call so we don't need a separate seed mutation. Returns the new
  9. * count so the client can show optimistic updates if it wants.
  10. */
  11. export default mutation(async (ctx: Ctx, args: Args) => {
  12. const id = args.id ?? 'default';
  13. const by = args.by ?? 1;
  14. await ctx.db.unsafe(
  15. `INSERT INTO counters (id, count) VALUES ($1, $2)
  16. ON CONFLICT (id) DO UPDATE SET count = counters.count + EXCLUDED.count`,
  17. [id, by],
  18. );
  19. const [row] = await ctx.db('counters').select(['count']).where({ id }).limit(1);
  20. return { id, count: Number(row?.count ?? 0) };
  21. });