feat(api): projects routes

Add lib/api/routes/projects.js: list by space (with status filter),
create scoped to space, get/patch/delete by id. FK violation from
unknown space_id maps to 400 invalid_space.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
root
2026-05-31 16:39:31 +10:00
parent ebb1e836ca
commit beb6da21c8
3 changed files with 142 additions and 0 deletions

View File

@@ -2,12 +2,15 @@ import { Router } from 'express';
import { ownerOnly } from '../auth/owner.js';
import { errorMiddleware, NotFoundError } from './errors.js';
import { router as spacesRouter } from './routes/spaces.js';
import { router as projectsRouter, spacesScopedRouter as projectsBySpaceRouter } from './routes/projects.js';
export function mountApi(app) {
const api = Router();
api.use(ownerOnly);
api.use('/spaces', spacesRouter);
api.use('/spaces/:space_id/projects', projectsBySpaceRouter);
api.use('/projects', projectsRouter);
api.use((_req, _res, next) => next(new NotFoundError('route not found')));

View File

@@ -0,0 +1,79 @@
import { Router } from 'express';
import { z } from 'zod';
import * as repo from '../../db/repos/projects.js';
import { validate } from '../validate.js';
import { NotFoundError, ValidationError, asyncWrap } from '../errors.js';
const STATUSES = ['idea', 'active', 'paused', 'done', 'abandoned'];
const createSchema = z.object({
slug: z.string().min(1).max(64).regex(/^[a-z0-9-]+$/),
name: z.string().min(1).max(200),
description: z.string().optional(),
status: z.enum(STATUSES).optional(),
started_at: z.string().datetime().nullable().optional()
});
const patchSchema = z.object({
slug: z.string().min(1).max(64).regex(/^[a-z0-9-]+$/).optional(),
name: z.string().min(1).max(200).optional(),
description: z.string().nullable().optional(),
status: z.enum(STATUSES).optional(),
started_at: z.string().datetime().nullable().optional(),
completed_at: z.string().datetime().nullable().optional()
});
const idParams = z.object({ id: z.string().uuid() });
const spaceParams = z.object({ space_id: z.string().uuid() });
export const spacesScopedRouter = Router({ mergeParams: true });
export const router = Router();
spacesScopedRouter.get('/',
validate({ params: spaceParams, query: z.object({ status: z.enum(STATUSES).optional() }) }),
asyncWrap(async (req, res) => {
res.json(await repo.listBySpace(req.params.space_id, { status: req.validatedQuery.status }));
})
);
spacesScopedRouter.post('/',
validate({ params: spaceParams, body: createSchema }),
asyncWrap(async (req, res) => {
try {
const row = await repo.create({ ...req.body, space_id: req.params.space_id }, req.actor);
res.status(201).json(row);
} catch (e) {
if (e.code === '23503') throw new ValidationError('invalid space', { space_id: req.params.space_id });
throw e;
}
})
);
router.get('/:id',
validate({ params: idParams }),
asyncWrap(async (req, res) => {
const row = await repo.getById(req.params.id);
if (!row) throw new NotFoundError('project not found');
res.json(row);
})
);
router.patch('/:id',
validate({ params: idParams, body: patchSchema }),
asyncWrap(async (req, res) => {
const existing = await repo.getById(req.params.id);
if (!existing) throw new NotFoundError('project not found');
const row = await repo.update(req.params.id, req.body, req.actor);
res.json(row);
})
);
router.delete('/:id',
validate({ params: idParams }),
asyncWrap(async (req, res) => {
const existing = await repo.getById(req.params.id);
if (!existing) throw new NotFoundError('project not found');
await repo.del(req.params.id, req.actor);
res.status(204).end();
})
);

View File

@@ -0,0 +1,60 @@
import { describe, it, expect, beforeAll, beforeEach } from 'vitest';
import request from 'supertest';
import { setup } from './helpers.js';
import * as spaces from '../../lib/db/repos/spaces.js';
let app, ownerHeaders, space;
const owner = { kind: 'user', id: null };
beforeAll(async () => { ({ app, ownerHeaders } = await setup()); });
beforeEach(async () => {
space = await spaces.create({ slug: `s-${Date.now()}`, name: 'S' }, owner);
});
describe('projects routes', () => {
it('POST creates with space scope', async () => {
const res = await request(app).post(`/api/spaces/${space.id}/projects`).set(ownerHeaders)
.send({ slug: 'p', name: 'Proj' });
expect(res.status).toBe(201);
expect(res.body.space_id).toBe(space.id);
});
it('POST with unknown space → 400 invalid_space', async () => {
const res = await request(app)
.post('/api/spaces/00000000-0000-0000-0000-000000000000/projects').set(ownerHeaders)
.send({ slug: 'p', name: 'Proj' });
expect(res.status).toBe(400);
expect(res.body.error.code).toBe('validation_failed');
});
it('GET list filters by status', async () => {
await request(app).post(`/api/spaces/${space.id}/projects`).set(ownerHeaders)
.send({ slug: 'a', name: 'A', status: 'active' });
await request(app).post(`/api/spaces/${space.id}/projects`).set(ownerHeaders)
.send({ slug: 'b', name: 'B', status: 'idea' });
const res = await request(app)
.get(`/api/spaces/${space.id}/projects?status=idea`).set(ownerHeaders);
expect(res.status).toBe(200);
expect(res.body.length).toBe(1);
expect(res.body[0].status).toBe('idea');
});
it('PATCH flips status to done without auto-setting completed_at', async () => {
const c = await request(app).post(`/api/spaces/${space.id}/projects`).set(ownerHeaders)
.send({ slug: 'p', name: 'P' });
const res = await request(app).patch(`/api/projects/${c.body.id}`).set(ownerHeaders)
.send({ status: 'done' });
expect(res.status).toBe(200);
expect(res.body.status).toBe('done');
expect(res.body.completed_at).toBeNull();
});
it('DELETE then GET → 404', async () => {
const c = await request(app).post(`/api/spaces/${space.id}/projects`).set(ownerHeaders)
.send({ slug: 'gone', name: 'Gone' });
const del = await request(app).delete(`/api/projects/${c.body.id}`).set(ownerHeaders);
expect(del.status).toBe(204);
const g = await request(app).get(`/api/projects/${c.body.id}`).set(ownerHeaders);
expect(g.status).toBe(404);
});
});