Skip to content

Commit

Permalink
feat: ✨ Add validation decorators,class-validator to DTO
Browse files Browse the repository at this point in the history
  • Loading branch information
zhumeisongsong committed Nov 27, 2024
1 parent 624c562 commit a4e2dd6
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
44 changes: 44 additions & 0 deletions libs/users/interface-adapters/src/lib/dto/user.dto.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,48 @@ describe('UserDto', () => {
expect(userDto.email).toBe(email);
expect(userDto.firstName).toBe(firstName);
});

it('should handle empty firstName and lastName', () => {
const id = '456';
const email = '[email protected]';
const userDto = new UserDto(id, email, null, null);

expect(userDto).toBeDefined();
expect(userDto.id).toBe(id);
expect(userDto.email).toBe(email);
expect(userDto.firstName).toBeUndefined();
expect(userDto.lastName).toBeUndefined();
});

it('should validate email format', () => {
const id = '789';
const invalidEmail = 'invalid-email';

expect(() => {
new UserDto(id, invalidEmail, null, null);
}).toThrow();
});

it('should require id and email', () => {
expect(() => {
// @ts-expect-error testing invalid constructor args
new UserDto();
}).toThrow();

expect(() => {
// @ts-expect-error testing invalid constructor args
new UserDto('123');
}).toThrow();
});

it('should handle special characters in names', () => {
const id = '101';
const email = '[email protected]';
const firstName = 'Jean-Pierre';
const lastName = "O'Connor";
const userDto = new UserDto(id, email, firstName, lastName);

expect(userDto.firstName).toBe(firstName);
expect(userDto.lastName).toBe(lastName);
});
});
6 changes: 5 additions & 1 deletion libs/users/interface-adapters/src/lib/dto/user.dto.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { IsEmail, IsString } from 'class-validator';
import { Field, ID, ObjectType } from '@nestjs/graphql';

@ObjectType()
Expand All @@ -6,12 +7,15 @@ export class UserDto {
id: string;

@Field()
@IsEmail()
email: string;

@Field()
firstName: string | null;
@IsString()
firstName?: string | null;

@Field()
@IsString()
lastName: string | null;

constructor(
Expand Down

0 comments on commit a4e2dd6

Please sign in to comment.