'How to validate request in typeorm controller
I have created a sample application to save data for a user. I wanted to know how to validate it before saving and showing the response in JSON. I have got a reference link but its not using a controller.
Please suggest a solution using a controller. Below is my code
Entity file:
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
age: number;
}
Controller file:
import {getRepository} from "typeorm"; import {NextFunction, Request, Response} from "express"; import {User} from "../entity/User";
export class UserController {
private userRepository = getRepository(User);
async all(request: Request, response: Response, next: NextFunction) {
return this.userRepository.find();
}
async one(request: Request, response: Response, next: NextFunction) {
return this.userRepository.findOne(request.params.id);
}
async save(request: Request, response: Response, next: NextFunction) {
return this.userRepository.save(request.body);
}
async remove(request: Request, response: Response, next: NextFunction) {
let userToRemove = await this.userRepository.findOne(request.params.id);
await this.userRepository.remove(userToRemove);
}
}
I wanted to validate firstname
and lastname
as mandatory i.e. no blank value should be accepted and age should take no blank values and numbers only.
Solution 1:[1]
Yes you can by using validate function in model class:
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
age: number;
@BeforeInsert()
@BeforeUpdate()
async validate() {
await validateOrReject(this);
}
}
Solution 2:[2]
You can use the class-validator and class-transformer package. Define the structure of JSON as a typescript class and add decorators from class-validator package.
export class UserStructure {
@IsString()
firstName: string;
@IsString()
lastName: string;
age: number;
}
Use class transformer to convert plain object to UserStructure Class and then pass the class to validate function which is imported from class-validator package for performing validation
import { plainToClass } from 'class-transformer';
import {validate} from 'class-validator';
//Place the following code inside your controller
let userStructureClass = plainToClass(UserStructure , req.body); //convert req.body plain object to UserStructure Class
let errors = await validate(userStructureClass);
if(errors.length > 0) req.json(errors)
- class-validator : https://www.npmjs.com/package/class-validator
- class-transformer : https://www.npmjs.com/package/class-transformer
NOTE : validate method only works for classes that is why we converted req.body plain object to class using class-transformer and then performed validation. These packages uses decorators so make sure to place the following in tsconfig.json
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Abdul Wasey |
Solution 2 | Afaq Javed |