diff --git a/lib/api/index.js b/lib/api/index.js index 072deb0..6c13eff 100644 --- a/lib/api/index.js +++ b/lib/api/index.js @@ -9,6 +9,7 @@ import { projectsScopedRouter as tasksByProjectRouter } from './routes/tasks.js'; import { router as pagesRouter, spacesScopedRouter as pagesBySpaceRouter } from './routes/pages.js'; +import { router as refsRouter } from './routes/refs.js'; export function mountApi(app) { const api = Router(); @@ -22,6 +23,7 @@ export function mountApi(app) { api.use('/projects/:project_id/tasks', tasksByProjectRouter); api.use('/tasks', tasksRouter); api.use('/pages', pagesRouter); + api.use('/refs', refsRouter); api.use((_req, _res, next) => next(new NotFoundError('route not found'))); diff --git a/lib/api/routes/refs.js b/lib/api/routes/refs.js new file mode 100644 index 0000000..9f98fab --- /dev/null +++ b/lib/api/routes/refs.js @@ -0,0 +1,111 @@ +import { Router } from 'express'; +import { z } from 'zod'; +import * as repo from '../../db/repos/refs.js'; +import { validate } from '../validate.js'; +import { parsePagination } from '../pagination.js'; +import { NotFoundError, ValidationError, asyncWrap } from '../errors.js'; + +const KINDS = ['url', 'video', 'pdf', 'image', 'file']; + +const baseFields = { + space_id: z.string().uuid(), + kind: z.enum(KINDS), + source_url: z.string().url().nullable().optional(), + title: z.string().max(500).nullable().optional(), + description: z.string().nullable().optional(), + summary: z.string().nullable().optional(), + body_text: z.string().nullable().optional(), + blob_path: z.string().nullable().optional(), + thumbnail: z.string().nullable().optional(), + metadata: z.record(z.string(), z.any()).optional(), + status: z.string().optional(), + source_kind: z.string().nullable().optional(), + external_id: z.string().nullable().optional(), + captured_at: z.string().datetime().optional() +}; + +const createSchema = z.object(baseFields); +const upsertSchema = z.object({ + ...baseFields, + source_kind: z.string().min(1), + external_id: z.string().min(1) +}); +const patchSchema = z.object(Object.fromEntries( + Object.entries(baseFields).map(([k, v]) => [k, v.optional()]) +)).partial(); + +const idParams = z.object({ id: z.string().uuid() }); + +export const router = Router(); + +router.get('/', + validate({ query: z.object({ + space_id: z.string().uuid().optional(), + kind: z.enum(KINDS).optional(), + limit: z.string().optional(), + offset: z.string().optional() + })}), + asyncWrap(async (req, res) => { + const { limit, offset } = parsePagination(req); + res.json(await repo.list({ + space_id: req.validatedQuery.space_id, + kind: req.validatedQuery.kind, + limit, offset + })); + }) +); + +router.post('/', + validate({ body: createSchema }), + asyncWrap(async (req, res) => { + try { + const row = await repo.create(req.body, req.actor); + res.status(201).json(row); + } catch (e) { + if (e.code === '23503') throw new ValidationError('invalid space', { space_id: req.body.space_id }); + throw e; + } + }) +); + +router.post('/upsert', + validate({ body: upsertSchema }), + asyncWrap(async (req, res) => { + try { + const row = await repo.upsertByExternal(req.body, req.actor); + res.json(row); + } catch (e) { + if (e.code === '23503') throw new ValidationError('invalid space', { space_id: req.body.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('ref 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('ref 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('ref not found'); + await repo.del(req.params.id, req.actor); + res.status(204).end(); + }) +); diff --git a/tests/api/refs.test.js b/tests/api/refs.test.js new file mode 100644 index 0000000..cbfbc08 --- /dev/null +++ b/tests/api/refs.test.js @@ -0,0 +1,53 @@ +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()}-${Math.random().toString(36).slice(2,5)}`, name: 'S' }, owner); +}); + +describe('refs routes', () => { + it('POST creates URL ref', async () => { + const res = await request(app).post('/api/refs').set(ownerHeaders).send({ + space_id: space.id, kind: 'url', source_url: 'https://example.com', title: 'Ex' + }); + expect(res.status).toBe(201); + expect(res.body.kind).toBe('url'); + }); + + it('GET ?kind=url filters', async () => { + await request(app).post('/api/refs').set(ownerHeaders).send({ + space_id: space.id, kind: 'url', source_url: 'https://a.example', title: 'A' + }); + await request(app).post('/api/refs').set(ownerHeaders).send({ + space_id: space.id, kind: 'pdf', blob_path: '/b.pdf', title: 'B' + }); + const res = await request(app).get(`/api/refs?space_id=${space.id}&kind=url`).set(ownerHeaders); + expect(res.body.length).toBe(1); + expect(res.body[0].kind).toBe('url'); + }); + + it('POST /upsert returns same id on repeat with same external_id', async () => { + const first = await request(app).post('/api/refs/upsert').set(ownerHeaders).send({ + space_id: space.id, kind: 'url', source_url: 'https://x', title: 'X', + source_kind: 'karakeep', external_id: 'abc' + }); + expect(first.status).toBe(200); + const second = await request(app).post('/api/refs/upsert').set(ownerHeaders).send({ + space_id: space.id, kind: 'url', source_url: 'https://x', title: 'X2', + source_kind: 'karakeep', external_id: 'abc' + }); + expect(second.body.id).toBe(first.body.id); + expect(second.body.title).toBe('X2'); + }); + + it('limit above max → 400', async () => { + const res = await request(app).get('/api/refs?limit=999').set(ownerHeaders); + expect(res.status).toBe(400); + }); +});