Skip to content

Commit

Permalink
feat: ✨ make GetUserUseCase be injectbale
Browse files Browse the repository at this point in the history
  • Loading branch information
zhumeisongsong committed Nov 20, 2024
1 parent 3886d0d commit fae29b5
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
import { GetUserUseCase } from './get-user.use-case';
import { UserRepository } from '@users/domain';
import { UsersRepository } from '@users/domain';

describe('GetUserUseCase', () => {
let getUserUseCase: GetUserUseCase;
let userRepository: jest.Mocked<UserRepository>;
let usersRepository: jest.Mocked<UsersRepository>;

beforeEach(() => {
userRepository = {
usersRepository = {
findById: jest.fn(),
} as unknown as jest.Mocked<UserRepository>;
} as unknown as jest.Mocked<UsersRepository>;

getUserUseCase = new GetUserUseCase(userRepository);
getUserUseCase = new GetUserUseCase(usersRepository);
});

describe('execute', () => {
it('should return a user when found', async () => {
const user = { id: '1', name: 'John Doe' };
userRepository.findById.mockResolvedValue(user);
usersRepository.findById.mockResolvedValue(user);

const result = await getUserUseCase.execute('1');

expect(result).toEqual(user);
expect(userRepository.findById).toHaveBeenCalledWith('1');
expect(usersRepository.findById).toHaveBeenCalledWith('1');
});

it('should return null when user is not found', async () => {
userRepository.findById.mockResolvedValue(null);
usersRepository.findById.mockResolvedValue(null);

const result = await getUserUseCase.execute('1');

expect(result).toBeNull();
expect(userRepository.findById).toHaveBeenCalledWith('1');
expect(usersRepository.findById).toHaveBeenCalledWith('1');
});
});
});
16 changes: 13 additions & 3 deletions libs/users/application/src/lib/use-cases/get-user.use-case.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import { User, UserRepository } from '@users/domain';
import { Inject, Injectable } from '@nestjs/common';
import { User, USERS_REPOSITORY, UsersRepository } from '@users/domain';

@Injectable()
export class GetUserUseCase {
constructor(private readonly userRepository: UserRepository) {}
constructor(
@Inject(USERS_REPOSITORY)
private readonly usersRepository: UsersRepository,
) {}

async execute(id: string): Promise<User | null> {
return this.userRepository.findById(id);
const user = this.usersRepository.findById(id);

if (!user) {
return null;
}
return user;
}
}
2 changes: 2 additions & 0 deletions libs/users/domain/src/lib/users.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ import { User } from './user.entity';
export interface UsersRepository {
findById(id: string): Promise<User | null>;
}

export const USERS_REPOSITORY = Symbol('USERS_REPOSITORY');

0 comments on commit fae29b5

Please sign in to comment.