feat(params): schema-aware arg decorators; async validating resolveArgs
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+83
-18
No files matched your search
+2
-2
@@ -114,7 +114,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
steps: [],
|
||||
handlerName: route.handlerName,
|
||||
needs: getHandlerNeeds(argSpecs),
|
||||
run: (c: any) => inst[route.handlerName](...resolveArgs(argSpecs, c)),
|
||||
run: async (c: any) => inst[route.handlerName](...(await resolveArgs(argSpecs, c))),
|
||||
transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
|
||||
duplicates: route.duplicates,
|
||||
});
|
||||
@@ -358,7 +358,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
headers: req.headers, inbound, abort,
|
||||
protocol: (req.socket as any).encrypted ? 'https' : 'http', ip: req.socket.remoteAddress ?? '' };
|
||||
for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; }
|
||||
const out = plan.run(ctx);
|
||||
const out = await plan.run(ctx);
|
||||
if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
|
||||
return out as AsyncIterable<unknown>;
|
||||
},
|
||||
|
||||
+23
-9
@@ -1,12 +1,14 @@
|
||||
import 'reflect-metadata';
|
||||
import type { Ctor } from './metadata';
|
||||
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
|
||||
import { ValidationError } from './signals';
|
||||
|
||||
export type Query = Record<string, string>;
|
||||
export type Headers = Record<string, string | string[] | undefined>;
|
||||
export type Context = Record<string, unknown>;
|
||||
|
||||
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
|
||||
export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[] }
|
||||
export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[]; schema?: StandardSchemaV1 }
|
||||
|
||||
const ARGS = Symbol('gt:args');
|
||||
|
||||
@@ -21,13 +23,17 @@ function record(target: object, methodKey: string | symbol | undefined, spec: Ar
|
||||
}
|
||||
|
||||
function envelope(source: ArgSource) {
|
||||
return (arg?: string | string[]): ParameterDecorator =>
|
||||
return (arg?: string | string[] | StandardSchemaV1, schema?: StandardSchemaV1): ParameterDecorator =>
|
||||
(target, methodKey, index) => {
|
||||
const spec: ArgSpec = Array.isArray(arg)
|
||||
? { index, source, keys: arg }
|
||||
: typeof arg === 'string'
|
||||
? { index, source, key: arg }
|
||||
: { index, source };
|
||||
const spec: ArgSpec = { index, source };
|
||||
if (Array.isArray(arg)) spec.keys = arg;
|
||||
else if (typeof arg === 'string') spec.key = arg;
|
||||
else if (isStandardSchema(arg)) spec.schema = arg;
|
||||
else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`);
|
||||
if (schema !== undefined) {
|
||||
if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`);
|
||||
spec.schema = schema;
|
||||
}
|
||||
record(target, methodKey, spec);
|
||||
};
|
||||
}
|
||||
@@ -62,11 +68,19 @@ export function getHandlerNeeds(specs: ArgSpec[]): string[] {
|
||||
return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string);
|
||||
}
|
||||
|
||||
export function resolveArgs(specs: ArgSpec[], context: Context): unknown[] {
|
||||
export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<unknown[]> {
|
||||
if (specs.length === 0) return [];
|
||||
const max = Math.max(...specs.map((s) => s.index));
|
||||
const args: unknown[] = new Array(max + 1).fill(undefined);
|
||||
for (const s of specs) args[s.index] = resolveOne(s, context);
|
||||
for (const s of specs) {
|
||||
let value = resolveOne(s, context);
|
||||
if (s.schema) {
|
||||
const result = await s.schema['~standard'].validate(value);
|
||||
if (result.issues) throw new ValidationError([...result.issues], s.source);
|
||||
value = result.value;
|
||||
}
|
||||
args[s.index] = value;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
|
||||
+58
-7
@@ -1,6 +1,7 @@
|
||||
import 'reflect-metadata';
|
||||
import { expect, test, describe, it } from 'vitest';
|
||||
import { needs, ctx, param, query, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
|
||||
import { needs, ctx, param, query, body, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
|
||||
import { ValidationError } from '../src/signals';
|
||||
|
||||
class Ctl {
|
||||
handler(
|
||||
@@ -27,13 +28,13 @@ test('getHandlerNeeds extracts only @needs keys', () => {
|
||||
expect(getHandlerNeeds(getArgs(Ctl, 'handler'))).toEqual(['user']);
|
||||
});
|
||||
|
||||
test('resolveArgs builds positional args from context', () => {
|
||||
test('resolveArgs builds positional args from context', async () => {
|
||||
const context = {
|
||||
user: { id: 'u1' },
|
||||
params: { id: '7' },
|
||||
query: { a: '1', b: '2', c: '3' },
|
||||
};
|
||||
const args = resolveArgs(getArgs(Ctl, 'handler'), context);
|
||||
const args = await resolveArgs(getArgs(Ctl, 'handler'), context);
|
||||
expect(args[0]).toEqual({ id: 'u1' });
|
||||
expect(args[1]).toBe('7');
|
||||
expect(args[2]).toEqual({ a: '1', b: '2', c: '3' });
|
||||
@@ -41,18 +42,18 @@ test('resolveArgs builds positional args from context', () => {
|
||||
expect(args[4]).toBe(context);
|
||||
});
|
||||
|
||||
test('a handler with no arg decorators resolves to no args', () => {
|
||||
test('a handler with no arg decorators resolves to no args', async () => {
|
||||
class Bare { ping() { return 1; } }
|
||||
expect(resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
|
||||
expect(await resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
|
||||
});
|
||||
|
||||
describe('@inbound / @abort', () => {
|
||||
it('resolves inbound and abort from reserved context keys, not as bags', () => {
|
||||
it('resolves inbound and abort from reserved context keys, not as bags', async () => {
|
||||
class Ctl { handle(@inbound() inc: AsyncIterable<unknown>, @abort() sig: AbortSignal) { return [inc, sig]; } }
|
||||
const specs = getArgs(Ctl, 'handle');
|
||||
const ac = new AbortController();
|
||||
const inc = (async function* () {})();
|
||||
const args = resolveArgs(specs, { inbound: inc, abort: ac.signal });
|
||||
const args = await resolveArgs(specs, { inbound: inc, abort: ac.signal });
|
||||
expect(args[0]).toBe(inc);
|
||||
expect(args[1]).toBe(ac.signal);
|
||||
});
|
||||
@@ -62,3 +63,53 @@ describe('@inbound / @abort', () => {
|
||||
expect(getHandlerNeeds(getArgs(Ctl, 'handle'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
const numFromStr = {
|
||||
'~standard': {
|
||||
version: 1 as const, vendor: 'test',
|
||||
validate: (v: unknown) => {
|
||||
const n = Number(v);
|
||||
return Number.isNaN(n) ? { issues: [{ message: 'not a number', path: ['n'] }] } : { value: n };
|
||||
},
|
||||
},
|
||||
};
|
||||
const asyncSchema = {
|
||||
'~standard': { version: 1 as const, vendor: 'test', validate: async (v: unknown) => ({ value: `async:${v}` }) },
|
||||
};
|
||||
|
||||
describe('resolveArgs validation', () => {
|
||||
it('valid: substitutes the parsed/coerced value; ctx source untouched', async () => {
|
||||
class C { m(@query(numFromStr) _q: number) {} }
|
||||
const specs = getArgs(C, 'm');
|
||||
const ctx: any = { query: '42' };
|
||||
const args = await resolveArgs(specs, ctx);
|
||||
expect(args[0]).toBe(42);
|
||||
expect(ctx.query).toBe('42');
|
||||
});
|
||||
it('invalid: throws ValidationError with source', async () => {
|
||||
class C { m(@body(numFromStr) _b: number) {} }
|
||||
const specs = getArgs(C, 'm');
|
||||
await expect(resolveArgs(specs, { body: 'nope' })).rejects.toBeInstanceOf(ValidationError);
|
||||
await resolveArgs(specs, { body: 'nope' }).catch((e) => { expect(e.source).toBe('body'); expect(e.issues[0].message).toBe('not a number'); });
|
||||
});
|
||||
it('async schema is awaited', async () => {
|
||||
class C { m(@body(asyncSchema) _b: string) {} }
|
||||
const args = await resolveArgs(getArgs(C, 'm'), { body: 'x' });
|
||||
expect(args[0]).toBe('async:x');
|
||||
});
|
||||
it('@param(name, schema) validates the named param (slot-2 schema)', async () => {
|
||||
class C { m(@param('id', numFromStr) _id: number) {} }
|
||||
const args = await resolveArgs(getArgs(C, 'm'), { params: { id: '7' } });
|
||||
expect(args[0]).toBe(7);
|
||||
});
|
||||
it('non-schema decorators unchanged: @body("key"), @body(), @query(["a","b"])', async () => {
|
||||
class C { m(@body('x') _x: any, @body() _b: any, @query(['a', 'b']) _q: any) {} }
|
||||
const args = await resolveArgs(getArgs(C, 'm'), { body: { x: 1, y: 2 }, query: { a: 'A', b: 'B', c: 'C' } });
|
||||
expect(args[0]).toBe(1);
|
||||
expect(args[1]).toEqual({ x: 1, y: 2 });
|
||||
expect(args[2]).toEqual({ a: 'A', b: 'B' });
|
||||
});
|
||||
it('decoration-time guard: a non-schema object throws', () => {
|
||||
expect(() => { class C { m(@body({} as any) _b: any) {} } return C; }).toThrow();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user