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