Skip to content

Instantly share code, notes, and snippets.

@victor-shelepen
Created March 13, 2023 08:24
Show Gist options
  • Save victor-shelepen/378d0c2b7492d8707a3d88d04fe02bb1 to your computer and use it in GitHub Desktop.
Save victor-shelepen/378d0c2b7492d8707a3d88d04fe02bb1 to your computer and use it in GitHub Desktop.
To receive data from the network, validate it, and transform it using class-validator and class-transformer, you can follow these steps:
async function createUser(userData: any): Promise<Document> {
const user = plainToClass(User, userData, { excludeExtraneousValues: true });
const errors = await validate(user);
if (errors.length > 0) {
throw new Error(`Validation failed: ${JSON.stringify(errors)}`);
}
const createdUser = await model('User').create(user);
return createdUser;
}
import { IsString, IsMongoId } from 'class-validator';
import { Transform, Type } from 'class-transformer';
import { Schema, Document, model } from 'mongoose';
class User {
@Transform(({ value }) => Schema.Types.ObjectId(value), { toClassOnly: true })
@Type(() => String)
@IsMongoId()
_id: Schema.Types.ObjectId;
@IsString()
name: string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment