NestJS - Add additional metadata to Pipes - nestjs

Is there a way to add additional metadata to a NestJS pipe?
The metadata property has these values:
export interface ArgumentMetadata {
type: 'body' | 'query' | 'param' | 'custom';
metatype?: Type<any>;
data?: string;
}
See: https://docs.nestjs.com/pipes

I was able to add additional metadata via a custom parameter decorator, and a custom pipe.
import { createParamDecorator} from '#nestjs/common'
export const ExtractIdFromBody = createParamDecorator(
(
{
property,
entityLookupProperty = 'id'
}: {
property: string
entityLookupProperty?: string
},
req
) => {
const value = get(req.body, property)
return {
value,
entityLookupProperty // the extra property
}
}
)
Then I used a the decorator like this:
#Post()
#UsePipes(new ValidationPipe({ transform: true }))
async doThing(
#ExtractIdFromBody({ property: 'userId', entityLookupProperty: 'someProperty' }, GetEntityOr404Pipe) entity: Entity,
): Promise<Entity[]> {
return await this.Service.doThing(entity)
}

Related

Class-Validator (Node.js) Get another property value within custom validation

At the moment, I have a very simple class-validator file with a ValidationPipe in Nest.js as follows:
import {
IsDateString,
IsEmail,
IsOptional,
IsString,
Length,
Max,
} from 'class-validator';
export class UpdateUserDto {
#IsString()
id: string;
#Length(2, 50)
#IsString()
firstName: string;
#IsOptional()
#Length(2, 50)
#IsString()
middleName?: string;
#Length(2, 50)
#IsString()
lastName: string;
#IsEmail()
#Max(255)
email: string;
#Length(8, 50)
password: string;
#IsDateString()
dateOfBirth: string | Date;
}
Lets say in the above "UpdateUserDto," the user passes an "email" field. I want to build a custom validation rule through class-validator such that:
Check if email address is already taken by a user from the DB
If the email address is already in use, check if the current user (using the value of 'id' property) is using it, if so, validation passes, otherwise, if it is already in use by another user, the validation fails.
While checking if the email address is already in use is a pretty simple task, how would you be able to pass the values of other properties within the DTO to a custom decorator #IsEmailUsed
It was pretty simple to solve, I solved it by creating a custom class-validation Decorator as below:
import { PrismaService } from '../../prisma/prisma.service';
import {
registerDecorator,
ValidationOptions,
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
} from 'class-validator';
import { Injectable } from '#nestjs/common';
#ValidatorConstraint({ name: 'Unique', async: true })
#Injectable()
export class UniqueConstraint implements ValidatorConstraintInterface {
constructor(private readonly prisma: PrismaService) {}
async validate(value: any, args: ValidationArguments): Promise<boolean> {
const [model, property = 'id', exceptField = null] = args.constraints;
if (!value || !model) return false;
const record = await this.prisma[model].findUnique({
where: {
[property]: value,
},
});
if (record === null) return true;
if (!exceptField) return false;
const exceptFieldValue = (args.object as any)[exceptField];
if (!exceptFieldValue) return false;
return record[exceptField] === exceptFieldValue;
}
defaultMessage(args: ValidationArguments) {
return `${args.property} entered is not valid`;
}
}
export function Unique(
model: string,
uniqueField: string,
exceptField: string = null,
validationOptions?: ValidationOptions,
) {
return function (object: any, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [model, uniqueField, exceptField],
validator: UniqueConstraint,
});
};
}
However, to allow DI to that particular Decorator, you need to also add this to your main.ts bootstrap function:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
...
// Line below needs to be added.
useContainer(app.select(AppModule), { fallbackOnErrors: true });
...
}
Also, make sure to import the "Constraint" in the app module:
#Module({
imports: ...,
controllers: [AppController],
providers: [
AppService,
PrismaService,
...,
// Line below added
UniqueConstraint,
],
})
export class AppModule {}
Finally, add it to your DTO as such:
export class UpdateUserDto {
#IsString()
id: string;
#IsEmail()
#Unique('user', 'email', 'id') // Adding this will check in the user table for a user with email entered, if it is already taken, it will check if it is taken by the same current user, and if so, no issues with validation, otherwise, validation fails.
email: string;
}
Luckily for us, the class-validator provides a very handy useContainer function, which allows setting the container to be used by the class-validor library.
So add this code in your main.ts file (app variable is your Nest application instance):
useContainer(app.select(AppModule), { fallbackOnErrors: true });
It allows the class-validator to use the NestJS dependency injection container.
#ValidatorConstraint({ name: 'emailId', async: true })
#Injectable()
export class CustomEmailvalidation implements ValidatorConstraintInterface {
constructor(private readonly prisma: PrismaService) {}
async validate(value: string, args: ValidationArguments): Promise<boolean> {
return this.prisma.user
.findMany({ where: { email: value } })
.then((user) => {
if (user) return false;
return true;
});
}
defaultMessage(args: ValidationArguments) {
return `Email already exist`;
}
}
Don't forget to declare your injectable classes as providers in the appropriate module.
Now you can use your custom validation constraint. Simply decorate the class property with #Validate(CustomEmailValidation) decorator:
export class CreateUserDto {
#Validate(customEmailValidation)
email: string;
name: string;
mobile: number;
}
If the email already exists in the database, you should get an error with the default message "Email already exists". Although using #Validate() is fine enough, you can write your own decorator, which will be much more convenient. Having written Validator Constraint is quick and easy. We need to just write decorator factory with registerDecorator() function.
export function Unique(validationOptions?: ValidationOptions) {
return function (object: any, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: CustomEmailvalidation,
});
};
}
As you can see, you can either write new validator logic or use written before validator constraint (in our case - Unique class).
Now we can go back to our User class and use the #Unique validator instead of the #Validate(CustomEmailValidation) decorator.
export class CreateUserDto {
#Unique()
email: string;
name: string;
mobile: number;
}
I think your first use case (Check if email address is already taken by a user from the DB), can be solved by using custom-validator
For the second one there is no option to get the current user before the validation. Suppose you are getting the current user using the #CurrentUser decorator. Then once the normal dto validation is done, you need to check inside the controller or service if the current user is accessing your resource.

class-transformer does not work : Transform function is not called

I try to use class-transformer but i can't do it.
I also use type-graphql and #typegoose/typegoose
Here's my code:
My Decorator
import { Transform } from 'class-transformer';
export function Trim() {
console.log('DECORATOR');
return Transform(({ value }: { value: string }) => {
console.log('value: ', value);
return value.trim();
});
}
My InputType
import { IsEmail } from 'class-validator';
import { InputType, Field } from 'type-graphql';
import { User } from '../Entities/User';
import { Trim } from '../../Decorators/Sanitize';
#InputType({ description: 'Input for user creation' })
export class AddUserInput implements Partial<User> {
#Field()
#Trim()
#IsEmail({ domain_specific_validation: true, allow_utf8_local_part: false })
email!: string;
}
My Resolver
import { Arg, Mutation, Resolver } from 'type-graphql';
import { User } from '../Entities/User';
import { AddUserInput } from '../Types/UsersInputs';
#Resolver(() => User)
export class UserResolvers {
#Mutation(() => String, { description: 'Register an admin' })
async createAccount(#Arg('data') data: AddUserInput): Promise<string> {
console.log({ ...data });
return data.email;
}
}
My Entity
import { prop, getModelForClass } from '#typegoose/typegoose';
import { ObjectType, Field } from 'type-graphql';
#ObjectType({ description: 'User model' })
export class User {
#Field({ description: 'The user email' })
#prop({ required: true, unique: true, match: [/\S+#\S+\.\S+/, 'is invalid'] })
email!: string;
}
export const UserModel = getModelForClass(User, {
schemaOptions: { timestamps: true }
});
My Request
POST http://localhost:5000/app HTTP/1.1
Content-Type: application/json
X-REQUEST-TYPE: GraphQL
mutation
{
createAccount (data : {
email: " email#gmail.com ",
})
}
The problem is that the console.log('value: ', value) inside Transform function is never call and my email is not trim.
Also console.log('DECORATOR') is not call when I do the request but just one time when server starting.
Thanks !
Typegoose transpiles classes into mongoose schemas & models, it does not apply any validation / transformation aside from mongoose provided ones, so your class-transformer decorators would only be called when using the class directly and using its functions. (like plainToClass and classToPlain)
In your case, it would be better to either use PropOptions get & set or pre-hooks.
As a note, typegoose provides a guide for using class-transformer with typegoose classes Integration Example: class-transformer, just to show that it can be used like normal classes.
Also note, it is currently recommended against using class-transformer because of mentioned issues inside the documentation.

Class-Transformer: access request object or pass in additional metadata?

I need to transform some file URL's in the response, the file paths need to contain the client id,
I have a shared class 'AssetReponseImagesDTO' this is used in lots of other classes, I need to transform the value of filename from a local path to append the CDN URL and client id and return a proper URL
I can get the CDN URL from the configService as it's just a string, to get the value of ClientId i have a custom decorator for nest.js - tried to use this decorator to access the same Id within the response but it doesn't work - seems to just return a string of the actual function
I also tried to create a new ClientId property on my top-level response DTO however the lower level Type such as AssetResponseImagesDTO won't have access to the parent's properties (unless I'm mistaken?)
Is there a way to pass in additional information to class-transformer which can then be referenced during the transform process?
export class AssetResponseImagesDTO {
#Expose({ name: 'url' })
#Transform(({ value }) =>
value ? `${configService.getCDNUrl()}${NEED_CLIENT_ID_HERE}}/asset/${value}` : null,
)
filename: string;
#Expose()
caption: string;
#Expose({ name: 'link' })
url: string;
}
Updated for more detail
Top-level response DTO
export class NewVehicleDetailResponseWrapperDTO {
#Type(() => NewVehicleResponseDTO)
vehicle: NewVehicle;
#Type(() => AssetResponseDTO)
assets: Asset[];
constructor(vehicle, assets) {
this.vehicle = vehicle;
this.assets = assets;
}
}
AssetResponseDTO
#Exclude()
export class AssetResponseDTO {
#Expose({ name: 'type' })
#Transform(({ value }) => AssetType[value])
assetType: AssetType;
#Expose({ name: 'name' })
scrapName: string;
#Expose({ name: 'images' })
#Type(() => AssetResponseImagesDTO)
assetImages: AssetImages[];
#Expose({ name: 'snippet' })
#Transform(({ value }) => value?.snippet)
#Type(() => AssetSnippets)
assetSnippet: AssetSnippets;
#Expose({ name: 'content' })
#Transform(({ value }) => value?.article)
#Type(() => AssetContents)
assetContent: AssetContents;
}
ClientId Decorator
export const ClientId = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
// We need to set the clientId either via a query param or from the logged in user.
let clientId;
if (request.user.clientId) {
clientId = request.user.clientId;
}
if (request.headers['x-client-id']) {
clientId = request.headers['x-client-id'];
}
if (!clientId) {
throw new BadRequestException();
}
return clientId;
},
);

How to write #Param and #Body in one DTO

I am using nestjs and I make an effort DTO's and I generate update-todo.dto.ts like this.
How can I use #Param and #Body together in one DTO?
#Param('id') id: string,
#Body('status') status: TodoStatus
So how to convert my code?
import { TodoStatus } from '../todo.model';
export class UpdateTodoDto {
id: string;
status: TodoStatus;
}
#Patch('/:id/status')
updateTodoStatus(
#Param('id') id: string,
#Body('status') status: TodoStatus
// convert this line
): Todo {
return this.todosService.updateTodoStatus(id, status);
}
You'd need, four components to work together.
A custom decorator to combine the #Param() and #Body() decorators
A DTO to hold the shape of the #Param() DTO
A DTO to hold the shape of the #Body() DTO
A DTO to combine the body and param DTOs
This repository goes through an example with an optional body based on a query parameter.
1
export const BodyAndParam = createParamDecorator((data: unknwon, ctx: ExecutionContext) => {
const req = ctx.switchToHttp().getRequest();
return { body: req.body, params: req.params };
});
2
export class ParamsDTO {
#IsString()
id: string;
}
3
export class BodyDTO {
#IsString()
hello: string;
}
4
export class MixedDTO {
#Type(() => ParamsDTO)
params: ParamsDTO;
#Type(() => BodyDTO);
body: BodyDTO;
}
Use
#Controller()
export class FooController {
#Post()
bar(#BodyAndParam() bodyAndParam: MixedDTO) {
// do stuff here
}
}

How to test Validation pipe is throwing the expect error for improperly shaped request on NestJS

I'm using NestJS 7.0.2 and have globally enabled validation pipes via app.useGlobalPipes(new ValidationPipe());.
I'd like to be able to have a unit test that verifies that errors are being thrown if the improperly shaped object is provided, however the test as written still passes. I've seen that one solution is to do this testing in e2e via this post, but I'm wondering if there is anything I'm missing that would allow me to do this in unit testing.
I have a very simple controller with a very simple DTO.
Controller
async myApi(#Body() myInput: myDto): Promise<myDto | any> {
return {};
}
DTO
export class myDto {
#IsNotEmpty()
a: string;
#IsNotEmpty()
b: string | Array<string>
}
Spec file
describe('generate', () => {
it('should require the proper type', async () => {
const result = await controller.generate(<myDto>{});
// TODO: I expect a validation error to occur here so I can test against it.
expect(result).toEqual({})
})
})
It also fails if I do not coerce the type of myDto and just do a ts-ignore on a generic object.
Just test your DTO with ValidationPipe:
it('validate DTO', async() => {
let target: ValidationPipe = new ValidationPipe({ transform: true, whitelist: true });
const metadata: ArgumentMetadata = {
type: 'body',
metatype: myDto,
data: ''
};
await target.transform(<myDto>{}, metadata)
.catch(err => {
expect(err.getResponse().message).toEqual(["your validation error"])
})
});
You can find here complete test examples for ValidationPipe in Nestjs code repository
To test custom ValidationPipe:
let target = new ValidationDob();
const metadata: ArgumentMetadata = {
type: 'query',
metatype: GetAgeDto,
data: '',
};
it('should throw error when dob is invalid', async () => {
try {
await target.transform(<GetAgeDto>{ dob: 'null' }, metadata);
expect(true).toBe(false);
} catch (err) {
expect(err.getResponse().message).toEqual('Invalid dob timestamp');
}
});

Resources