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: ✨ import getUserUseCase in UsersService #58

Merged
merged 15 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from 10 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ You can use `npx nx list` to get a list of installed plugins. Then, run `npx nx
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| resolver(interface-adapters) | Define GraphQL schema and resolver. |
| dto(interface-adapters) | Define DTOs for GraphQL schema. |
| 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., MongooseUserRepository). |
| 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). |
| 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. |
| entity(domain) | Define core business entities and business rules.<br/> Maintain entity independence from database and framework. |
Expand Down
4 changes: 2 additions & 2 deletions apps/users/src/users/users.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import {
} from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { UsersService } from '@users/application';
import { UsersService, GetUserUseCase } from '@users/application';
import { UsersResolver } from '@users/interface-adapters';
import { DatabaseModule } from '@shared/infrastructure-mongoose';

@Module({
providers: [UsersResolver, UsersService],
providers: [UsersResolver, UsersService, GetUserUseCase],
imports: [
GraphQLModule.forRoot<ApolloFederationDriverConfig>({
driver: ApolloFederationDriver,
Expand Down
2 changes: 1 addition & 1 deletion libs/users/application/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export * from './lib/use-case/get-user.use-case';
export * from './lib/use-cases/get-user.use-case';

// service
export * from './lib/users.service';
21 changes: 14 additions & 7 deletions libs/users/application/src/lib/users.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { Test, TestingModule } from '@nestjs/testing';
import { User } from '@users/domain';

import { UsersService } from './users.service';
import { GetUserUseCase } from './use-cases/get-user.use-case';

describe('UsersService', () => {
let service: UsersService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
providers: [UsersService, GetUserUseCase],
}).compile();

service = module.get<UsersService>(UsersService);
Expand All @@ -18,13 +19,19 @@ describe('UsersService', () => {
expect(service).toBeDefined();
});

it('should return a user by id', () => {
const user: User | undefined = service.findById('1');
expect(user).toEqual({ id: '1', name: 'John Doe' });
it('should return a user by id', async () => {
const user = new User('1', 'John Doe');
jest.spyOn(service, 'findById').mockResolvedValue(user);

const result = await service.findById('1');
expect(result).toEqual(user);
});

it('should return undefined if user is not found', () => {
const user: User | undefined = service.findById('3');
expect(user).toBeUndefined();
it('should return null if user is not found', async () => {
jest.spyOn(service, 'findById').mockResolvedValue(null);

const result = await service.findById('1');
expect(result).toBeNull();

});
});
11 changes: 5 additions & 6 deletions libs/users/application/src/lib/users.service.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { Injectable } from '@nestjs/common';
import { User } from '@users/domain';

import { GetUserUseCase } from './use-cases/get-user.use-case';

@Injectable()
export class UsersService {
private users: User[] = [
{ id: '1', name: 'John Doe' },
{ id: '2', name: 'Richard Roe' },
];
constructor(private readonly getUserUseCase: GetUserUseCase) {}

findById(id: string): User | undefined {
return this.users.find((user) => user.id === id);
async findById(id: string): Promise<User | null> {
return this.getUserUseCase.execute(id);
}
}
3 changes: 1 addition & 2 deletions libs/users/domain/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
// user
export * from './lib/user.entity';
export * from './lib/user.repository';
export * from './lib/users.repository';
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { UserRepository } from './user.repository';
import { UsersRepository } from './users.repository';
import { User } from './user.entity';

class MockUserRepository implements UserRepository {
class MockUsersRepository implements UsersRepository {
private users: User[] = [
{ id: '1', name: 'John Doe' },
{ id: '2', name: 'Jane Doe' },
Expand All @@ -12,20 +12,20 @@ class MockUserRepository implements UserRepository {
}
}

describe('UserRepository', () => {
let userRepository: UserRepository;
describe('UsersRepository', () => {
let usersRepository: UsersRepository;

beforeEach(() => {
userRepository = new MockUserRepository();
usersRepository = new MockUsersRepository();
});

test('findById should return a user by id', async () => {
const user = await userRepository.findById('1');
const user = await usersRepository.findById('1');
expect(user).toEqual({ id: '1', name: 'John Doe' });
});

test('findById should return null if user not found', async () => {
const user = await userRepository.findById('3');
const user = await usersRepository.findById('3');
expect(user).toBeNull();
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { User } from './user.entity';

export interface UserRepository {
export interface UsersRepository {
findById(id: string): Promise<User | null>;
}
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 1 addition & 1 deletion libs/users/infrastructure/mongoose/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './lib/mongoose-user.repository';
export * from './lib/mongoose-users.repository';
export * from './lib/user.schema';
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { MongooseUserRepository } from './mongoose-user.repository';
import { MongooseUsersRepository } from './mongoose-users.repository';
import { UserDocument } from './user.schema';
import { User } from '@users/domain';

describe('MongooseUserRepository', () => {
let repository: MongooseUserRepository;
describe('MongooseUsersRepository', () => {
let repository: MongooseUsersRepository;
let userModel: Model<UserDocument>;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
MongooseUserRepository,
MongooseUsersRepository,
{
provide: getModelToken(UserDocument.name),
useValue: {
Expand All @@ -22,7 +22,7 @@ describe('MongooseUserRepository', () => {
],
}).compile();

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

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { User, UserRepository } from '@users/domain';
import { User, UsersRepository } from '@users/domain';
import { Model } from 'mongoose';

import { UserDocument } from './user.schema';

export class MongooseUserRepository implements UserRepository {
@Injectable()
export class MongooseUsersRepository implements UsersRepository {
constructor(
@InjectModel(UserDocument.name) private userModel: Model<UserDocument>,
) {}

async findById(id: string): Promise<User | null> {
const userDoc = await this.userModel.findById(id).exec();
return userDoc ? new User(userDoc.id, userDoc.name) : null;

if (!userDoc) {
return null;
}
return new User(userDoc.id, userDoc.name);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,40 +30,19 @@ describe('UsersResolver', () => {
});

describe('getUser', () => {
it('should return a user by id', () => {
const user: User = { id: '1', name: 'John Doe' };
jest.spyOn(service, 'findById').mockReturnValue(user);
it('should return a user by id', async () => {
const user = new User('1', 'John Doe');
jest.spyOn(service, 'findById').mockResolvedValue(user);

expect(resolver.getUser('1')).toEqual(user);
expect(service.findById).toHaveBeenCalledWith('1');
const result = await resolver.getUser('1');
expect(result).toEqual(user);
});

it('should return undefined if user not found', () => {
jest.spyOn(service, 'findById').mockReturnValue(undefined);
it('should return undefined if user not found', async () => {
jest.spyOn(service, 'findById').mockResolvedValue(null);

expect(resolver.getUser('2')).toBeNull();
expect(service.findById).toHaveBeenCalledWith('2');
});
});

describe('resolveReference', () => {
it('should return a user by reference id', () => {
const user: User = { id: '1', name: 'John Doe' };
jest.spyOn(service, 'findById').mockReturnValue(user);

expect(
resolver.resolveReference({ __typename: 'User', id: '1' }),
).toEqual(user);
expect(service.findById).toHaveBeenCalledWith('1');
});

it('should return undefined if user not found by reference id', () => {
jest.spyOn(service, 'findById').mockReturnValue(undefined);

expect(
resolver.resolveReference({ __typename: 'User', id: '2' }),
).toBeUndefined();
expect(service.findById).toHaveBeenCalledWith('2');
const result = await resolver.getUser('1');
expect(result).toBeNull();
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved
});
});
});
16 changes: 3 additions & 13 deletions libs/users/interface-adapters/src/lib/resolver/users.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Args, ID, Query, Resolver, ResolveReference } from '@nestjs/graphql';
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,16 +8,7 @@ export class UsersResolver {
constructor(private usersService: UsersService) {}

@Query(() => UserDto, { nullable: true })
getUser(@Args({ name: 'id', type: () => ID }) id: string): UserDto | null {
const user: User | undefined = this.usersService.findById(id); // Domain entity
return user ? new UserDto(user.id, user.name) : null;
}

@ResolveReference()
resolveReference(reference: {
__typename: string;
id: string;
}): User | undefined {
return this.usersService.findById(reference.id);
getUser(@Args({ name: 'id', type: () => ID }) id: string): Promise<UserDto | null> {
return this.usersService.findById(id);
}
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved
}
Loading