05 Validations - jp7io/typescript-crud-api GitHub Wiki

Validations

Add class-validator

yarn add class-validator

Set validations for articles

code ./src/entity/Article.ts
import { Length } from 'class-validator';

  ...

  @Column()
  @Length(3, 50)
  title: string;

  @Column()
  @Length(3, 500)
  text: string;

  ...

Set validations for authors

code ./src/entity/Author.ts
import { Length } from 'class-validator';

  ...

  @Column()
  @Length(3, 50)
  name: string;

  ...

Add validations and error handling in the records controller

code ./src/controllers/records.ts
import { 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 };
};

Test application

yarn dev
curl -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}

Commit

git add .
git commit -m "Validations"

Next step: Rate Limit

⚠️ **GitHub.com Fallback** ⚠️