Skip to content

Commit

Permalink
feat: make get user by id use case
Browse files Browse the repository at this point in the history
  • Loading branch information
patricks-js committed Nov 23, 2024
1 parent c97ca79 commit dc128db
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/application/use-cases/get-user-by-id.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { ResourceNotFoundError } from "@/application/errors/resource-not-found";
import type { IUserRepository } from "@/domain/repositories/user-repository";
import { InMemoryUserRepository } from "@/infra/repositories/in-memory/in-memory-user-repository";
import { GetUserByIdUseCase } from "./get-user-by-id";

describe("GetUserByIdUseCase", () => {
let userRepository: IUserRepository;
let getUserByIdUseCase: GetUserByIdUseCase;

beforeEach(() => {
userRepository = new InMemoryUserRepository();
getUserByIdUseCase = new GetUserByIdUseCase(userRepository);
});

afterEach(() => {
vi.resetAllMocks();
});

it("should be able to return the user when found", async () => {
const input = { id: "123" };

userRepository.findById = vi.fn().mockResolvedValue({
id: "123",
});

const { user } = await getUserByIdUseCase.execute(input);

expect(user).toEqual(
expect.objectContaining({
id: "123",
}),
);
expect(userRepository.findById).toHaveBeenCalledWith("123");
expect(userRepository.findById).toHaveBeenCalledTimes(1);
});

it("should throw ResourceNotFoundError when user is not found", async () => {
const input = { id: "123" };

userRepository.findById = vi.fn().mockResolvedValue(null);

await expect(getUserByIdUseCase.execute(input)).rejects.toThrow(
ResourceNotFoundError,
);
expect(userRepository.findById).toHaveBeenCalledWith("123");
expect(userRepository.findById).toHaveBeenCalledOnce();
});
});
30 changes: 30 additions & 0 deletions src/application/use-cases/get-user-by-id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { User } from "@/domain/entities/user";
import type { UseCase } from "@/domain/interfaces/use-case";
import type { IUserRepository } from "@/domain/repositories/user-repository";
import { ResourceNotFoundError } from "../errors/resource-not-found";

export type GetUserByIdInput = {
id: string;
};

export type GetUserByIdOutput = {
user: User;
};

export class GetUserByIdUseCase
implements UseCase<GetUserByIdInput, GetUserByIdOutput>
{
constructor(private readonly userRepository: IUserRepository) {}

async execute(input: GetUserByIdInput): Promise<GetUserByIdOutput> {
const user = await this.userRepository.findById(input.id);

if (!user) {
throw new ResourceNotFoundError("User");
}

return {
user,
};
}
}

0 comments on commit dc128db

Please sign in to comment.