-
Notifications
You must be signed in to change notification settings - Fork 0
05 Validations
JP Barbosa edited this page Apr 17, 2021
·
2 revisions
yarn add class-validatorcode ./src/entity/Article.tsimport { Length } from 'class-validator';
...
@Column()
@Length(3, 50)
title: string;
@Column()
@Length(3, 500)
text: string;
...code ./src/entity/Author.tsimport { Length } from 'class-validator';
...
@Column()
@Length(3, 50)
name: string;
...code ./src/controllers/records.tsimport { Repository } from 'typeorm';
import { Request, Response } from 'express';
import { validate } from 'class-validator';
export const recordsController = <T>(repository: Repository<T>) => {
const wrap = (fn: Function) => {
return (req: Request, res: Response) => {
fn(req, res).catch((e: Error) => {
res.status(400).send(e);
});
};
};
const findAll = wrap(async (req: Request, res: Response) => {
...
});
const findOne = wrap(async (req: Request, res: Response) => {
...
});
const create = wrap(async (req: Request, res: Response) => {
// create a new record
const record = repository.create(req.body);
const validation = await validate(record);
if (validation.length) {
return res.status(422).send({ validation });
}
const results = await repository.save(record);
return res.send(results);
});
const update = wrap(async (req: Request, res: Response) => {
...
});
const remove = wrap(async (req: Request, res: Response) => {
...
});
return { findAll, findOne, create, update, remove };
};yarn devcurl -X POST -H "Content-Type: application/json" \
-d '{"name":""}' \
http://localhost:4000/authors
# {"validation":[{..."constraints":{"isLength":"name must be longer than or equal to 3 characters"}}]}curl -X POST -H "Content-Type: application/json" \
-d '{"name":"Author Name"}' \
http://localhost:4000/authors
# {"name":"Author Name","id":2}curl -X POST -H "Content-Type: application/json" \
-d '{"title":"", "text":""}' \
http://localhost:4000/articles
# {"validation":[{..."constraints":{"isLength":"title must be longer than or equal to 3 characters"}},{..."constraints":{"isLength":"text must be longer than or equal to 3 characters"}}]}curl -X POST -H "Content-Type: application/json" \
-d '{"title":"Article With Author", "text":"Article Text"}' \
http://localhost:4000/articles
# {"title":"Article Title","text":"Article Text", "id":3}git add .
git commit -m "Validations"