All files / src/routes accounts.ts

100% Statements 12/12
100% Branches 4/4
100% Functions 4/4
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38              7x 2x       7x       2x 2x   2x 1x     1x 1x 1x         1x     1x        
import type { FastifyInstance } from "fastify";
import { db } from "../db/index.js";
import { accounts, memberships } from "../db/schema.js";
import { getUserAccounts } from "../lib/accounts.js";
 
export async function accountRoutes(app: FastifyInstance) {
  // GET /accounts — list user's accounts with role
  app.get("/accounts", { preHandler: [app.authenticate] }, async (request) => {
    return getUserAccounts(request.user.sub);
  });
 
  // POST /accounts — create a new account (user becomes owner)
  app.post<{ Body: { name: string } }>(
    "/accounts",
    { preHandler: [app.authenticate] },
    async (request, reply) => {
      const userId = request.user.sub;
      const { name } = request.body;
 
      if (!name || typeof name !== "string") {
        return reply.status(400).send({ error: "Account name is required" });
      }
 
      const account = await db.transaction(async (tx) => {
        const [created] = await tx.insert(accounts).values({ name }).returning();
        await tx.insert(memberships).values({
          userId,
          accountId: created.id,
          role: "owner",
        });
        return created;
      });
 
      return reply.status(201).send({ id: account.id, name: account.name, role: "owner" });
    },
  );
}