Params
Usually, params decorators are created by using createCustomDecorator(handle,name)
.
demo-http/src/params/validated-body.ts
import type { ControllerParamsContext } from '@triptyk/nfw-http';
import { createCustomDecorator } from '@triptyk/nfw-http';
import type { ObjectSchema } from 'yup';
export const validatedBody = async (schema: ObjectSchema<any>, context: ControllerParamsContext<unknown>) => {
return schema.validate(context.ctx.request.body);
};
export function ValidatedBody (schema: ObjectSchema<any>) {
return createCustomDecorator((context) => validatedBody(schema, context), 'validated-body');
}
To test the behavior, externalize the handle
method used as the first parameter.
demo-http/tests/param.test.ts
import 'reflect-metadata';
import type { ControllerParamsContext } from '@triptyk/nfw-http';
import { validatedBody } from '../src/params/validated-body.js';
import { userSchema } from '../src/validations/user.js';
import { ValidationError } from 'yup';
it('Throws error when schema is not valid', async () => {
const fakeContext = {
ctx: {
request: {
body: {}
}
}
} as ControllerParamsContext<unknown>;
expect(() => validatedBody(userSchema, fakeContext)).rejects.toThrowError(ValidationError);
});
it('Returns body when is valid', async () => {
const fakeContext = {
ctx: {
request: {
body: {
name: 'Amaury'
}
}
}
} as ControllerParamsContext<unknown>;
const body = await validatedBody(userSchema, fakeContext);
expect(body).toStrictEqual(fakeContext.ctx.request.body);
});