class-validator
To validate request body, request headers and URL query, specify a class with class-validator instead of type for reqBody, reqHeaders and query.
Deprecated after 0.30.0
After frourio
and frourio-express
version 0.30.0
, using class-validator as a validator in Frourio is deprecated.
If used, a warning will be displayed during the build. Consider migrating to zod.
Example
Validator
server/validators/index.ts
import { MinLength, IsString } from 'class-validator';
export class LoginBody {
@MinLength(5)
id: string;
@MinLength(8)
pass: string;
}
export class TokenHeader {
@IsString()
@MinLength(10)
token: string;
}
API Definition
server/api/token/index.ts
import { LoginBody, TokenHeader } from '$/validators';
export type Methods = {
post: {
reqBody: LoginBody;
resBody: {
token: string;
};
};
delete: {
reqHeaders: TokenHeader;
};
};
Results
$ curl -X POST -H "Content-Type: application/json" -d '{"id":"correctId","pass":"correctPass"}' http://localhost:8080/api/token
{"token":"XXXXXXXXXX"}
$ curl -X POST -H "Content-Type: application/json" -d '{"id":"abc","pass":"12345"}' http://localhost:8080/api/token -i
HTTP/1.1 400 Bad Request
$ curl -X POST -H "Content-Type: application/json" -d '{"id":"incorrectId","pass":"incorrectPass"}' http://localhost:8080/api/token -i
HTTP/1.1 401 Unauthorized
Passing Validator Options
- Fastify
- Express
server/service/app.ts
import Fastify, { FastifyServerFactory } from 'fastify';
import server from '$/$server';
export const init = (serverFactory?: FastifyServerFactory) => {
const app = Fastify({ serverFactory });
server(app, { basePath: '/api', validator: { whitelist: true } });
return app;
};
server/service/app.ts
import express from 'express';
import server from '$/$server';
export const init = () => {
const app = express();
server(app, { basePath: '/api', validator: { whitelist: true } });
return app;
};