feat: request pipeline with ctx accumulation, throw handling, lifecycle events

This commit is contained in:
chrnx committed 2026-06-26 00:47:55 -05:00
1 parent af4642d449
commit 23a31f9264
2 files changed
+73

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
import { Bus } from './bus';
import { errorToResponse } from './transformers';
import type { TransformerFn } from './metadata';
export interface PipelineStep { name: string; origin: string; run: (ctx: any) => any }
export interface ResponseShape { status: number; headers: Record<string, string>; body: string }
export async function runPipeline(args: {
steps: PipelineStep[];
handler: (ctx: any) => unknown;
transformer: TransformerFn;
seed: Record<string, unknown>;
bus: Bus;
}): Promise<ResponseShape> {
const { steps, handler, transformer, seed, bus } = args;
let ctx: any = { ...seed };
try {
for (const s of steps) {
bus.emit('request:step:enter', { name: s.name, scope: s.origin });
const out = await s.run(ctx);
ctx = { ...ctx, ...out };
bus.emit('request:step:leave', { name: s.name, scope: s.origin });
}
const result = await handler(ctx);
const r = transformer(result);
return { status: r.status ?? 200, headers: r.headers ?? {}, body: r.body };
} catch (error) {
bus.emit('request:step:error', { name: 'pipeline', error });
return errorToResponse(error);
}
}
+42
View File
@@ -0,0 +1,42 @@
import { expect, test, vi } from 'vitest';
import { runPipeline } from '../src/pipeline';
import { Bus } from '../src/bus';
import { JsonTransformer } from '../src/transformers';
import { Unauthorized } from '../src/signals';
const base = { transformer: JsonTransformer, seed: { req: { token: 'abc' } } };
test('runs steps, accumulates ctx, transforms handler return', async () => {
const bus = new Bus();
const res = await runPipeline({
...base, bus,
steps: [{ name: 'auth', origin: 'mod', run: (ctx) => ({ user: ctx.req.token }) }],
handler: (ctx) => ({ user: ctx.user }),
});
expect(res.status).toBe(200);
expect(JSON.parse(res.body)).toEqual({ user: 'abc' });
});
test('a thrown HttpError short-circuits to an error response', async () => {
const bus = new Bus();
const res = await runPipeline({
...base, bus,
steps: [{ name: 'auth', origin: 'mod', run: () => { throw new Unauthorized('no'); } }],
handler: () => ({ never: true }),
});
expect(res.status).toBe(401);
});
test('emits enter/leave/error lifecycle events', async () => {
const bus = new Bus();
const enter = vi.fn(); const error = vi.fn();
bus.on('request:step:enter', enter);
bus.on('request:step:error', error);
await runPipeline({
...base, bus,
steps: [{ name: 'boom', origin: 'mod', run: () => { throw new Unauthorized(); } }],
handler: () => ({}),
});
expect(enter).toHaveBeenCalledWith(expect.objectContaining({ name: 'boom' }));
expect(error).toHaveBeenCalled();
});