Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ✨ add new attributes to user #73

Merged
merged 15 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@ You can use `npx nx list` to get a list of installed plugins. Then, run `npx nx
| interface-adapters | It should not contain complex business logic. <br/>Responsible for receiving and processing requests from clients. These requests are interactions with external systems that need to be converted into operations that conform to the business logic through adapters.<br/>Relies on the Application layer for core business logic, avoiding direct interaction with databases or other external systems. |
| resolver(interface-adapters) | Handles GraphQL queries and mutations by converting them into calls to the application layer. <br/>Responsible for input validation and response formatting specific to GraphQL. |
| dto(interface-adapters) | Define DTOs for GraphQL schema. |
| infrastructure | Implements the technical capabilities needed to support the higher layers of the application. <br/>Handles database connections, external service integrations, and other technical concerns. <br/>Contains concrete implementations of repository interfaces defined in the domain layer. |
| infrastructure | Implements the technical capabilities needed to support the higher layers of the application.<br/> Handles database connections, external service integrations, and other technical concerns.<br/> Contains concrete implementations of repository interfaces defined in the domain layer. |

| mongoose(infrastructure) | Implements the repository interfaces defined in the domain layer using Mongoose as the ODM (Object Document Mapper). <br/>Includes Mongoose Schema definitions, database connection management, and concrete implementations of repository interfaces (e.g., MongooseUsersRepository). |
| mongoose(infrastructure) | Implements the repository interfaces defined in the domain layer using Mongoose as the ODM (Object Document Mapper).<br/> Includes Mongoose Schema definitions, database connection management, and concrete implementations of repository interfaces (e.g., MongooseUsersRepository).<br/> Adding validation in the Mongoose schema ensures that any data persisted to the database adheres to the required constraints. This helps maintain data integrity and prevents invalid or duplicate entries at the database level. |
| service(application) | As the core of the application layer, it mainly interacts with the domain layer and interface-adapter layer.<br/> If you migrate to a non-NestJS architecture in the future (e.g. other frameworks or microservices), the application tier code can be left unaffected. |
| use-case(application) | Define business use cases and encapsulate business logic. |
| use-case(application) | Define business use cases and encapsulate business logic.<br/> Implementing validation in the use-case layer allows you to enforce business logic and provide immediate feedback to users or calling services. This is where you can handle complex validation rules and provide detailed error messages.|
| entity(domain) | Define core business entities and business rules.<br/> Maintain entity independence from database and framework. |
| repository(domain) | Interfaces (or abstract classes), which define methods for manipulating data without concern for specific database implementations. <br/>By defining this interface, we can decouple database access: the specific details of data access will be done by implementation classes, such as specific implementations using tools like Mongoose, TypeORM, Prisma, and so on. |
| repository(domain) | Interfaces (or abstract classes), which define methods for manipulating data without concern for specific database implementations.<br/> By defining this interface, we can decouple database access: the specific details of data access will be done by implementation classes, such as specific implementations using tools like Mongoose, TypeORM, Prisma, and so on. |

## Useful links

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ describe('GetUserUseCase', () => {

describe('execute', () => {
it('should return user when found', async () => {
const mockUser = { id: '1', name: 'John Doe' };
const mockUser = {
id: '1',
email: '[email protected]',
firstName: 'John',
lastName: 'Doe',
};
(usersRepository.findById as jest.Mock).mockResolvedValue(mockUser);

const result = await getUserUseCase.execute('1');
Expand All @@ -32,4 +37,4 @@ describe('GetUserUseCase', () => {
expect(usersRepository.findById).toHaveBeenCalledWith('1');
});
});
});
});
7 changes: 6 additions & 1 deletion libs/users/application/src/lib/users.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,12 @@ describe('UsersService', () => {

describe('findById', () => {
it('should return a user if found', async () => {
const user: User = { id: '1', name: 'John Doe' };
const user: User = {
id: '1',
email: '[email protected]',
firstName: 'John',
lastName: 'Doe',
};
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved
jest.spyOn(getUserUseCase, 'execute').mockResolvedValue(user);

const result = await service.findById('1');
Expand Down
47 changes: 39 additions & 8 deletions libs/users/domain/src/lib/user.entity.spec.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,46 @@
import { User } from './user.entity';

describe('User Entity', () => {
it('should create a user with id and name', () => {
const user = new User('1', 'John Doe');
expect(user.id).toBe('1');
expect(user.name).toBe('John Doe');
it('should create a user with all required fields', () => {
const user = new User('123', '[email protected]', 'John', 'Doe');

expect(user.id).toBe('123');
expect(user.email).toBe('[email protected]');
expect(user.firstName).toBe('John');
expect(user.lastName).toBe('Doe');
});

it('should allow updating first name', () => {
const user = new User('123', '[email protected]', 'John', 'Doe');
user.firstName = 'Jane';
expect(user.firstName).toBe('Jane');
});

it('should allow updating last name', () => {
const user = new User('123', '[email protected]', 'John', 'Doe');
user.lastName = 'Smith';
expect(user.lastName).toBe('Smith');
});

it('should allow updating first name and last name', () => {
const user = new User('123', '[email protected]', 'John', 'Doe');
user.firstName = 'Jane';
user.lastName = 'Smith';
expect(user.firstName).toBe('Jane');
expect(user.lastName).toBe('Smith');
});

it('should allow null values for first name and last name', () => {
const user = new User('123', '[email protected]', null, null);
expect(user.firstName).toBeNull();
expect(user.lastName).toBeNull();
});

it('should allow updating the name', () => {
const user = new User('1', 'John Doe');
user.name = 'Jane Doe';
expect(user.name).toBe('Jane Doe');
it('should allow setting first name and last name to null', () => {
const user = new User('123', '[email protected]', 'John', 'Doe');
user.firstName = null;
user.lastName = null;
expect(user.firstName).toBeNull();
expect(user.lastName).toBeNull();
});
});
4 changes: 3 additions & 1 deletion libs/users/domain/src/lib/user.entity.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
export class User {
constructor(
public readonly id: string,
public name: string,
public readonly email: string,
public firstName: string | null,
public lastName: string | null,
) {}
}
16 changes: 13 additions & 3 deletions libs/users/domain/src/lib/users.repository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@ import { User } from './user.entity';

class MockUsersRepository implements UsersRepository {
private users: User[] = [
{ id: '1', name: 'John Doe' },
{ id: '2', name: 'Jane Doe' },
{ id: '1', email: '[email protected]', firstName: 'John', lastName: 'Doe' },
{
id: '2',
email: '[email protected]',
firstName: 'Jane',
lastName: 'Smith',
},
];

async findById(id: string): Promise<User | null> {
Expand All @@ -21,7 +26,12 @@ describe('UsersRepository', () => {

test('findById should return a user by id', async () => {
const user = await usersRepository.findById('1');
expect(user).toEqual({ id: '1', name: 'John Doe' });
expect(user).toEqual({
id: '1',
email: '[email protected]',
firstName: 'John',
lastName: 'Doe'
});
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved
});

test('findById should return null if user not found', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@ describe('MongooseUsersRepository', () => {
}).compile();

repository = module.get<MongooseUsersRepository>(MongooseUsersRepository);
userModel = module.get<Model<UserDocument>>(getModelToken(UserDocument.name));
userModel = module.get<Model<UserDocument>>(
getModelToken(UserDocument.name),
);
});

it('should return a user when found', async () => {
const mockUser = {
id: '507f1f77bcf86cd799439011',
name: 'Test User',
email: '[email protected]',
firstName: 'John',
lastName: 'Doe',
};

jest.spyOn(userModel, 'findById').mockReturnValue({
Expand All @@ -39,7 +43,9 @@ describe('MongooseUsersRepository', () => {
const user = await repository.findById(mockUser.id);
expect(user).toBeInstanceOf(User);
expect(user?.id).toBe(mockUser.id);
expect(user?.name).toBe(mockUser.name);
expect(user?.email).toBe(mockUser.email);
expect(user?.firstName).toBe(mockUser.firstName);
expect(user?.lastName).toBe(mockUser.lastName);
});

it('should return null when user is not found', async () => {
Expand All @@ -50,4 +56,4 @@ describe('MongooseUsersRepository', () => {
const user = await repository.findById('507f1f77bcf86cd799439011');
expect(user).toBeNull();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@ export class MongooseUsersRepository implements UsersRepository {
) {}

async findById(id: string): Promise<User | null> {

const _id = new Types.ObjectId(id);
const userDocument = await this.userModel.findById(_id).exec();

if (!userDocument) {
return null;
}
return new User(userDocument.id, userDocument.name);
return new User(
userDocument.id,
userDocument.email,
userDocument.firstName,
userDocument.lastName,
);
}
}
12 changes: 9 additions & 3 deletions libs/users/infrastructure/mongoose/src/lib/user.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@ import { Document } from 'mongoose';

@Schema()
export class UserDocument extends Document {
@Prop({ required: true })
name!: string;
// refactor: move match regex to a shared lib
@Prop({ required: true, unique: true, match: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ })
email!: string;
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved

@Prop({ required: false})
firstName!: string;
@Prop({ required: false })
lastName!: string;
}

export const UserSchema = SchemaFactory.createForClass(UserDocument);
export const UserSchema = SchemaFactory.createForClass(UserDocument);
9 changes: 6 additions & 3 deletions libs/users/interface-adapters/src/lib/dto/user.dto.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import { UserDto } from './user.dto';
describe('UserDto', () => {
it('should create a new UserDto instance', () => {
const id = '123';
const name = 'Test User';
const userDto = new UserDto(id, name);
const email = '[email protected]';
const firstName = 'John';
const lastName = 'Doe';
const userDto = new UserDto(id, email, firstName, lastName);
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved

expect(userDto).toBeDefined();
expect(userDto.id).toBe(id);
expect(userDto.name).toBe(name);
expect(userDto.email).toBe(email);
expect(userDto.firstName).toBe(firstName);
});
});
19 changes: 16 additions & 3 deletions libs/users/interface-adapters/src/lib/dto/user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,23 @@ export class UserDto {
id: string;

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

constructor(id: string, name: string) {
@Field()
firstName: string | null;

@Field()
lastName: string | null;
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved

constructor(
id: string,
email: string,
firstName: string | null,
lastName: string | null,
) {
this.id = id;
this.name = name;
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from '@users/application';
import { User } from '@users/domain';

import { UsersResolver } from './users.resolver';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Args, ID, Query, Resolver } from '@nestjs/graphql';
import { UsersService } from '@users/application';
import { User } from '@users/domain';

import { UserDto } from '../dto/user.dto';

Expand All @@ -9,12 +10,12 @@ export class UsersResolver {

@Query(() => UserDto, { nullable: true })
async getUser(@Args({ name: 'id', type: () => ID }) id: string): Promise<UserDto | null> {
const user = await this.usersService.findById(id);
const user: User| null = await this.usersService.findById(id);

if (!user) {
return null;
}

return new UserDto(user.id, user.name);
return new UserDto(user.id, user.email, user.firstName, user.lastName);
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@nestjs/mongoose": "^10.1.0",
"@nestjs/platform-express": "^10.4.7",
"axios": "^1.7.7",
"class-validator": "^0.14.1",
"graphql": "^16.9.0",
"graphql-tools": "^9.0.2",
"inlineTrace": "link:@apollo/server/plugin/inlineTrace",
Expand Down
Loading