feat: handler argument decorators (needs/ctx/param/query/body/headers)
This commit is contained in:
2 files changed
+123
No files matched your search
@@ -0,0 +1,47 @@
|
||||
import 'reflect-metadata';
|
||||
import { expect, test } from 'vitest';
|
||||
import { needs, ctx, param, query, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
|
||||
|
||||
class Ctl {
|
||||
handler(
|
||||
@needs('user') _user: unknown,
|
||||
@param('id') _id: unknown,
|
||||
@query() _q: unknown,
|
||||
@query(['a', 'b']) _sub: unknown,
|
||||
@ctx() _c: unknown,
|
||||
) { return null; }
|
||||
}
|
||||
|
||||
test('getArgs returns specs sorted by parameter index', () => {
|
||||
const specs = getArgs(Ctl, 'handler');
|
||||
expect(specs.map((s) => [s.index, s.source, s.key ?? s.keys])).toEqual([
|
||||
[0, 'needs', 'user'],
|
||||
[1, 'params', 'id'],
|
||||
[2, 'query', undefined],
|
||||
[3, 'query', ['a', 'b']],
|
||||
[4, 'ctx', undefined],
|
||||
]);
|
||||
});
|
||||
|
||||
test('getHandlerNeeds extracts only @needs keys', () => {
|
||||
expect(getHandlerNeeds(getArgs(Ctl, 'handler'))).toEqual(['user']);
|
||||
});
|
||||
|
||||
test('resolveArgs builds positional args from context', () => {
|
||||
const context = {
|
||||
user: { id: 'u1' },
|
||||
params: { id: '7' },
|
||||
query: { a: '1', b: '2', c: '3' },
|
||||
};
|
||||
const args = 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' });
|
||||
expect(args[3]).toEqual({ a: '1', b: '2' });
|
||||
expect(args[4]).toBe(context);
|
||||
});
|
||||
|
||||
test('a handler with no arg decorators resolves to no args', () => {
|
||||
class Bare { ping() { return 1; } }
|
||||
expect(resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
|
||||
});
|
||||
Reference in new issue
Block a user