Skip to content

Commit

Permalink
refactor(domain): refactored errors in the account and institutional …
Browse files Browse the repository at this point in the history
…domains

Refactored every use cases and respective tests in the account and institutional domains.
User already exists error, institution already exists error and unregistered institution error created.
Ci file for release altered to create prereleases in the alpha branch.
  • Loading branch information
ClaudionorOjr committed Nov 8, 2023
1 parent f4c6a44 commit ff959d8
Show file tree
Hide file tree
Showing 30 changed files with 359 additions and 131 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ on:
workflows: [Run Unit Tests]
types:
- completed
branches:
- alpha

jobs:
on-success:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { InMemoryStudentsRepository } from 'test/repositories/in-memory-students
import { InMemoryUsersRepository } from 'test/repositories/in-memory-users-repository'
import { makeStudent, makeUser } from 'test/factories/make-user'
import { InMemoryResponsiblesRepository } from 'test/repositories/in-memory-responsibles-repository'
import { UnregisteredUserError } from '@core/errors/unregistered-user-error'

let usersRepository: InMemoryUsersRepository
let studentsRepository: InMemoryStudentsRepository
Expand All @@ -27,22 +28,47 @@ describe('Edit student profile use case', () => {

it('should be able a student to edit your profile data', async () => {
const user = makeUser({}, 'user-01')
const student = await makeStudent({ userId: user.id })
const student = makeStudent({ userId: user.id })

await usersRepository.create(user)
await studentsRepository.create(student)

await sut.execute({
const result = await sut.execute({
userId: user.id,
completeName: 'John doe',
dateOfBirth: new Date('2002-03-12'),
})

expect(result.isSuccess()).toBe(true)
expect(usersRepository.users[0]).toMatchObject({
completeName: 'John doe',
})
expect(studentsRepository.students[0]).toMatchObject({
dateOfBirth: new Date('2002-03-12'),
})
})

it('should not be able a non-existent user to edit a profile data', async () => {
const result = await sut.execute({
userId: 'user-01',
completeName: 'John doe',
dateOfBirth: new Date('2002-03-12'),
})

expect(result.isFailure()).toBe(true)
expect(result.value).instanceOf(UnregisteredUserError)
})

it('should not be able a non-student user to edit a profile data', async () => {
await usersRepository.create(makeUser({}, 'user-01'))

const result = await sut.execute({
userId: 'user-01',
completeName: 'John doe',
dateOfBirth: new Date('2002-03-12'),
})

expect(result.isFailure()).toBe(true)
expect(result.value).instanceOf(UnregisteredUserError)
})
})
12 changes: 9 additions & 3 deletions src/domain/account/application/use-cases/edit-student-profile.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Either, failure, success } from '@core/either'
import { ResponsiblesRepository } from '../repositories/responsibles-repository'
import { StudentsRepository } from '../repositories/students-repository'
import { UsersRepository } from '../repositories/users-repository'
import { UnregisteredUserError } from '@core/errors/unregistered-user-error'

interface EditStudentProfileUseCaseRequest {
userId: string
Expand All @@ -12,6 +14,8 @@ interface EditStudentProfileUseCaseRequest {
degreeOfKinship?: string
}

type EditStudentProfileUseCaseResponse = Either<UnregisteredUserError, object>

export class EditStudentProfileUseCase {
constructor(
private usersRepository: UsersRepository,
Expand All @@ -27,17 +31,17 @@ export class EditStudentProfileUseCase {
responsibleName,
responsiblePhone,
degreeOfKinship,
}: EditStudentProfileUseCaseRequest): Promise<void> {
}: EditStudentProfileUseCaseRequest): Promise<EditStudentProfileUseCaseResponse> {
const user = await this.usersRepository.findById(userId)

if (!user) {
throw new Error('User not found.')
return failure(new UnregisteredUserError())
}

const student = await this.studentsRepository.findByUserId(userId)

if (!student) {
throw new Error('Student not found.')
return failure(new UnregisteredUserError())
}

user.completeName = completeName ?? user.completeName
Expand All @@ -62,5 +66,7 @@ export class EditStudentProfileUseCase {

await this.responsiblesRepository.save(responsible)
}

return success({})
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { UseCaseError } from '@core/errors/use-case-error'

export class UserAlreadyExistsError extends Error implements UseCaseError {
constructor() {
super('User already exists!')
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ describe('Fetch solicitations use case', () => {
await makeSolicitation({ status: 'REFUSED' }),
)

const { solicitations } = await sut.execute()
const result = await sut.execute()

expect(solicitations).toHaveLength(2)
expect(result.isSuccess()).toBe(true)
expect(result.value?.solicitations).toHaveLength(2)
expect(solicitationsRepository.solicitations).toHaveLength(3)
})
})
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import { Solicitation } from '@account/enterprise/entities/solicitation'
import { SolicitationsRepository } from '../repositories/solicitations-repository'
import { Either, success } from '@core/either'

interface FetchPendingSolicitationsUseCaseResponse {
solicitations: Solicitation[]
}
type FetchPendingSolicitationsUseCaseResponse = Either<
null,
{
solicitations: Solicitation[]
}
>

export class FetchPendingSolicitationsUseCase {
constructor(private solicitationsRepository: SolicitationsRepository) {}

async execute(): Promise<FetchPendingSolicitationsUseCaseResponse> {
const solicitations = await this.solicitationsRepository.list()

return { solicitations }
return success({ solicitations })
}
}
22 changes: 12 additions & 10 deletions src/domain/account/application/use-cases/register-admin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { InMemoryUsersRepository } from 'test/repositories/in-memory-users-repos
import { faker } from '@faker-js/faker'
import { makeUser } from 'test/factories/make-user'
import { FakeHasher } from 'test/cryptography/fake-hasher'
import { UserAlreadyExistsError } from './errors/user-already-exists-error'

let usersRepository: InMemoryUsersRepository
let fakeHasher: FakeHasher
Expand All @@ -17,14 +18,14 @@ describe('Register admin use case', () => {
})

it('should be able to register an admin', async () => {
await sut.execute({
const result = await sut.execute({
completeName: faker.person.fullName(),
email: faker.internet.email(),
password: '123456',
phone: faker.phone.number(),
})

expect(usersRepository.users).toHaveLength(1)
expect(result.isSuccess()).toBe(true)
expect(usersRepository.users[0].rule).toEqual('ADMIN')
})

Expand All @@ -51,13 +52,14 @@ describe('Register admin use case', () => {

await usersRepository.create(makeUser({ email }))

await expect(() => {
return sut.execute({
completeName: faker.person.fullName(),
email,
password: '123456',
phone: faker.phone.number(),
})
}).rejects.toBeInstanceOf(Error)
const result = await sut.execute({
completeName: faker.person.fullName(),
email,
password: '123456',
phone: faker.phone.number(),
})

expect(result.isFailure()).toBe(true)
expect(result.value).toBeInstanceOf(UserAlreadyExistsError)
})
})
10 changes: 8 additions & 2 deletions src/domain/account/application/use-cases/register-admin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { User } from '@core/entities/user'
import { UsersRepository } from '../repositories/users-repository'
import { HashGenerator } from '@account/cryptography/hash-generator'
import { Either, failure, success } from '@core/either'
import { UserAlreadyExistsError } from './errors/user-already-exists-error'

interface RegisterAdminUseCaseRequest {
completeName: string
Expand All @@ -9,6 +11,8 @@ interface RegisterAdminUseCaseRequest {
phone: string
}

type RegisterAdminUseCaseResponse = Either<UserAlreadyExistsError, object>

export class RegisterAdminUseCase {
constructor(
private usersRepository: UsersRepository,
Expand All @@ -20,11 +24,11 @@ export class RegisterAdminUseCase {
email,
password,
phone,
}: RegisterAdminUseCaseRequest): Promise<void> {
}: RegisterAdminUseCaseRequest): Promise<RegisterAdminUseCaseResponse> {
const userAlredyExists = await this.usersRepository.findByEmail(email)

if (userAlredyExists) {
throw new Error('User already exists!')
return failure(new UserAlreadyExistsError())
}

const passwordHash = await this.hashGenerator.hash(password)
Expand All @@ -38,5 +42,7 @@ export class RegisterAdminUseCase {
})

await this.usersRepository.create(admin)

return success({})
}
}
22 changes: 12 additions & 10 deletions src/domain/account/application/use-cases/register-driver.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { InMemoryUsersRepository } from 'test/repositories/in-memory-users-repos
import { faker } from '@faker-js/faker'
import { makeUser } from 'test/factories/make-user'
import { FakeHasher } from 'test/cryptography/fake-hasher'
import { UserAlreadyExistsError } from './errors/user-already-exists-error'

let usersRepository: InMemoryUsersRepository
let fakeHasher: FakeHasher
Expand All @@ -17,14 +18,14 @@ describe('Register driver use case', () => {
})

it('should be able to register a driver', async () => {
await sut.execute({
const result = await sut.execute({
completeName: faker.person.fullName(),
email: faker.internet.email(),
password: faker.string.alphanumeric(6),
phone: faker.phone.number(),
})

expect(usersRepository.users).toHaveLength(1)
expect(result.isSuccess()).toBe(true)
expect(usersRepository.users[0].rule).toEqual('DRIVER')
})

Expand All @@ -50,13 +51,14 @@ describe('Register driver use case', () => {

await usersRepository.create(makeUser({ email }))

await expect(() => {
return sut.execute({
completeName: faker.person.fullName(),
email,
password: '123456',
phone: faker.phone.number(),
})
}).rejects.toBeInstanceOf(Error)
const result = await sut.execute({
completeName: faker.person.fullName(),
email,
password: '123456',
phone: faker.phone.number(),
})

expect(result.isFailure()).toBe(true)
expect(result.value).toBeInstanceOf(UserAlreadyExistsError)
})
})
10 changes: 8 additions & 2 deletions src/domain/account/application/use-cases/register-driver.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { User } from '@core/entities/user'
import { UsersRepository } from '../repositories/users-repository'
import { HashGenerator } from '@account/cryptography/hash-generator'
import { Either, failure, success } from '@core/either'
import { UserAlreadyExistsError } from './errors/user-already-exists-error'

interface RegisterDriverUseCaseRequest {
completeName: string
Expand All @@ -9,6 +11,8 @@ interface RegisterDriverUseCaseRequest {
phone: string
}

type RegisterDriverUseCaseResponse = Either<UserAlreadyExistsError, object>

export class RegisterDriverUseCase {
constructor(
private usersRepository: UsersRepository,
Expand All @@ -20,11 +24,11 @@ export class RegisterDriverUseCase {
email,
password,
phone,
}: RegisterDriverUseCaseRequest): Promise<void> {
}: RegisterDriverUseCaseRequest): Promise<RegisterDriverUseCaseResponse> {
const userAlreadyExists = await this.usersRepository.findByEmail(email)

if (userAlreadyExists) {
throw new Error('User already exists!')
return failure(new UserAlreadyExistsError())
}

const passwordHash = await this.hashGenerator.hash(password)
Expand All @@ -38,5 +42,7 @@ export class RegisterDriverUseCase {
})

await this.usersRepository.create(driver)

return success({})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { InMemoryStudentsRepository } from 'test/repositories/in-memory-students
import { InMemoryUsersRepository } from 'test/repositories/in-memory-users-repository'
import { makeSolicitation } from 'test/factories/make-solicitation'
import { InMemoryResponsiblesRepository } from 'test/repositories/in-memory-responsibles-repository'
import { ResourceNotFoundError } from '@core/errors/resource-not-found-error'

let solicitationsRepository: InMemorySolicitationsRepository
let usersRepository: InMemoryUsersRepository
Expand Down Expand Up @@ -36,8 +37,9 @@ describe('Register student use case', () => {

expect(solicitationsRepository.solicitations).toHaveLength(1)

await sut.execute({ solicitationId: 'solicitation-01' })
const result = await sut.execute({ solicitationId: 'solicitation-01' })

expect(result.isSuccess()).toBe(true)
expect(solicitationsRepository.solicitations).toHaveLength(0)
expect(usersRepository.users).toHaveLength(1)
expect(studentsRepository.students).toHaveLength(1)
Expand All @@ -50,8 +52,9 @@ describe('Register student use case', () => {
})

it('should not be able to register a non-existent solicitation', async () => {
await expect(() =>
sut.execute({ solicitationId: 'solicitation-01' }),
).rejects.toBeInstanceOf(Error)
const result = await sut.execute({ solicitationId: 'solicitation-01' })

expect(result.isFailure()).toBe(true)
expect(result.value).toBeInstanceOf(ResourceNotFoundError)
})
})
Loading

0 comments on commit ff959d8

Please sign in to comment.