Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
101 lines
5.8 KiB
TypeScript
101 lines
5.8 KiB
TypeScript
import express from 'express';
|
|
import request from 'supertest';
|
|
import { PassThrough } from 'stream';
|
|
import { z } from 'zod';
|
|
|
|
jest.mock('../src/config/db', () => ({}));
|
|
jest.mock('../src/middleware/authMiddleware', () => ({ protect: jest.fn(), optionalAuth: jest.fn(), admin: jest.fn(), staff: jest.fn(), supervisor: jest.fn() }));
|
|
|
|
import { mount } from '../src/v2/route';
|
|
import { errorHandler } from '../src/v2/errors';
|
|
import { v1Route } from '../src/v2/viaV1';
|
|
import type { RequestHandler } from 'express';
|
|
|
|
function appWith(...defs: ReturnType<typeof v1Route>[]) {
|
|
const app = express();
|
|
app.use(express.json());
|
|
const router = express.Router();
|
|
mount(router, defs);
|
|
app.use('/api/v2', router);
|
|
app.use('/api/v2', errorHandler);
|
|
return app;
|
|
}
|
|
|
|
describe('v2 routes answered by v1 handlers', () => {
|
|
test("v1's JSON becomes data; v2's :id is given to v1 by its old name", async () => {
|
|
const handler: RequestHandler = (req, res) => { res.json({ eventId: req.params.eventId, q: req.query.x }); };
|
|
const app = appWith(v1Route({ method: 'get', path: '/things/:id', tag: 'T', summary: 's', access: 'public', v1: handler, map: ctx => ({ params: { eventId: ctx.params.id } }), params: z.object({ id: z.string() }) }));
|
|
const res = await request(app).get('/api/v2/things/e1?x=2');
|
|
expect(res.status).toBe(200);
|
|
expect(res.body).toEqual({ data: { eventId: 'e1', q: '2' } });
|
|
});
|
|
|
|
test("a v1 error is a v2 error, with v1's code as the reason", async () => {
|
|
const handler: RequestHandler = (_req, res) => { res.status(409).json({ message: 'Already closed.', code: 'EVENT_CLOSED' }); };
|
|
const app = appWith(v1Route({ method: 'post', path: '/close', tag: 'T', summary: 's', access: 'public', v1: handler }));
|
|
const res = await request(app).post('/api/v2/close').send({});
|
|
expect(res.status).toBe(409);
|
|
expect(res.body).toEqual({ error: { code: 'CONFLICT', message: 'Already closed.', reason: 'EVENT_CLOSED' } });
|
|
});
|
|
|
|
test('a thrown error and a next(err) both reach the error handler', async () => {
|
|
const thrower: RequestHandler = async () => { throw Object.assign(new Error('Nope.'), { statusCode: 403 }); };
|
|
const passer: RequestHandler = (_req, _res, next) => next(Object.assign(new Error('Missing.'), { statusCode: 404 }));
|
|
const app = appWith(
|
|
v1Route({ method: 'get', path: '/a', tag: 'T', summary: 's', access: 'public', v1: thrower }),
|
|
v1Route({ method: 'get', path: '/b', tag: 'T', summary: 's', access: 'public', v1: passer }),
|
|
);
|
|
expect((await request(app).get('/api/v2/a')).body.error).toMatchObject({ code: 'FORBIDDEN', message: 'Nope.' });
|
|
expect((await request(app).get('/api/v2/b')).body.error).toMatchObject({ code: 'NOT_FOUND', message: 'Missing.' });
|
|
});
|
|
|
|
test('middleware chains run in order', async () => {
|
|
const mark: RequestHandler = (req, _res, next) => { (req as unknown as { mark: string }).mark = 'yes'; next(); };
|
|
const handler: RequestHandler = (req, res) => { res.json({ mark: (req as unknown as { mark: string }).mark }); };
|
|
const app = appWith(v1Route({ method: 'get', path: '/m', tag: 'T', summary: 's', access: 'public', v1: [mark, handler] }));
|
|
expect((await request(app).get('/api/v2/m')).body).toEqual({ data: { mark: 'yes' } });
|
|
});
|
|
|
|
test('a file a v1 handler pipes is sent as a download', async () => {
|
|
const handler: RequestHandler = (_req, res) => {
|
|
res.setHeader('Content-Type', 'application/pdf');
|
|
res.setHeader('Content-Disposition', 'attachment; filename="ticket.pdf"');
|
|
const s = new PassThrough();
|
|
s.pipe(res);
|
|
s.write(Buffer.from('%PDF-1.4 '));
|
|
s.end(Buffer.from('end'));
|
|
};
|
|
const app = appWith(v1Route({ method: 'get', path: '/pdf', tag: 'T', summary: 's', access: 'public', file: { contentType: 'application/pdf' }, v1: handler }));
|
|
const res = await request(app).get('/api/v2/pdf').buffer(true).parse((r, cb) => { const c: Buffer[] = []; r.on('data', (d: Buffer) => c.push(d)); r.on('end', () => cb(null, Buffer.concat(c))); });
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers['content-type']).toContain('application/pdf');
|
|
expect(res.headers['content-disposition']).toContain('ticket.pdf');
|
|
expect((res.body as Buffer).toString()).toBe('%PDF-1.4 end');
|
|
});
|
|
|
|
test("a v1 router is given the v1 URL; one with no matching route is a 404", async () => {
|
|
const router = express.Router();
|
|
router.get('/today', (req, res) => { res.json({ q: req.query.x }); });
|
|
const app = appWith(
|
|
v1Route({ method: 'get', path: '/dash', tag: 'T', summary: 's', access: 'public', v1: router, map: ctx => ({ url: '/today?x=' + String(ctx.req.query.x) }) }),
|
|
v1Route({ method: 'get', path: '/nothing', tag: 'T', summary: 's', access: 'public', v1: router, map: () => ({ url: '/missing' }) }),
|
|
);
|
|
expect((await request(app).get('/api/v2/dash?x=7')).body).toEqual({ data: { q: '7' } });
|
|
const res = await request(app).get('/api/v2/nothing');
|
|
expect(res.status).toBe(404);
|
|
expect(res.body.error.code).toBe('NOT_FOUND');
|
|
});
|
|
|
|
test("a file v1 sends with res.download is a download", async () => {
|
|
const os = require("os"); const path = require("path");
|
|
const file = path.join(os.tmpdir(), "viaV1-test-backup.sql");
|
|
require("fs").writeFileSync(file, "-- backup");
|
|
const handler: RequestHandler = (_req, res) => { res.download(file, "backup.sql"); };
|
|
const app = appWith(v1Route({ method: "get", path: "/backup", tag: "T", summary: "s", access: "public", file: { contentType: "application/octet-stream" }, v1: handler }));
|
|
const res = await request(app).get("/api/v2/backup").buffer(true).parse((r, cb) => { const c: Buffer[] = []; r.on("data", (d: Buffer) => c.push(d)); r.on("end", () => cb(null, Buffer.concat(c))); });
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers["content-disposition"]).toContain("backup.sql");
|
|
expect((res.body as Buffer).toString()).toBe("-- backup");
|
|
});
|
|
});
|