Skip to content

Commit

Permalink
added base question module and create method
Browse files Browse the repository at this point in the history
  • Loading branch information
henriqueweiand committed Nov 3, 2023
1 parent d991601 commit 5583737
Show file tree
Hide file tree
Showing 32 changed files with 245 additions and 8 deletions.
1 change: 1 addition & 0 deletions src/modules/common/database/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './database.module';
export * from './repository/question.repositoy';
export * from './repository/user.repositoy';
export * from './prisma/prisma.service';
6 changes: 4 additions & 2 deletions src/modules/module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
import { UserModule } from './user/user.module';
import { QuestionModule } from './question/question.module';

@Module({
imports: [
UsersModule
UserModule,
QuestionModule
],
})
export class Modules { }
34 changes: 34 additions & 0 deletions src/modules/question/controllers/create-question.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {
Body,
Controller,
HttpCode,
HttpException,
HttpStatus,
NotFoundException,
Post
} from '@nestjs/common';
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
import { CreateQuestionDto } from '../dto/create-question.dto';
import { QuestionDto } from '../dto/question.dto';
import { CreateQuestionUseCase } from '../use-case/create-question';

@Controller('/question')
@ApiTags('question')
export class CreateQuestionController {
constructor(private createQuestionUseCase: CreateQuestionUseCase) { }

@ApiOkResponse({ type: QuestionDto })
@HttpCode(HttpStatus.CREATED)
@Post('')
handle(@Body() createQuestionDto: CreateQuestionDto) {
try {
const question = this.createQuestionUseCase.execute(createQuestionDto);
return question;
} catch (e) {
if (e instanceof NotFoundException) {
throw new HttpException('Author not found', HttpStatus.CONFLICT);
}
throw new HttpException('Was not possible to register', HttpStatus.BAD_REQUEST);
}
}
}
17 changes: 17 additions & 0 deletions src/modules/question/dto/create-question.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ApiProperty } from '@nestjs/swagger';
import {
IsNotEmpty,
IsString
} from 'class-validator';

export class CreateQuestionDto {
@ApiProperty()
@IsString()
@IsNotEmpty()
content: string;

@ApiProperty()
@IsString()
@IsNotEmpty()
authorId: string;
}
19 changes: 19 additions & 0 deletions src/modules/question/dto/question.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { ApiProperty } from '@nestjs/swagger';
import { Question } from '@prisma/client';

export class QuestionDto implements Question {
@ApiProperty()
id: string;

@ApiProperty()
content: string;

@ApiProperty()
createdAt: Date;

@ApiProperty()
updatedAt: Date;

@ApiProperty()
authorId: string;
}
12 changes: 12 additions & 0 deletions src/modules/question/question.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { DatabaseModule } from '@app/common';
import { Module } from '@nestjs/common';
import { CreateQuestionController } from './controllers/create-question.controller';
import { CreateQuestionUseCase } from './use-case/create-question';

@Module({
controllers: [CreateQuestionController],
imports: [DatabaseModule],
providers: [CreateQuestionUseCase],
exports: [],
})
export class QuestionModule { }
118 changes: 118 additions & 0 deletions src/modules/question/use-case/create-question.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { Test, TestingModule } from '@nestjs/testing';
import { QuestionRepository, UserRepository } from '@app/common';
import { CreateQuestionDto } from '../dto/create-question.dto';
import { Question, User } from '@prisma/client';
import { CreateQuestionUseCase } from './create-question';

class QuestionRepositoryMock {
create = jest.fn();
}

class UserRepositoryMock {
findById = jest.fn();
}

describe('CreateQuestionUseCase', () => {
let createQuestionUseCase: CreateQuestionUseCase;
let questionRepository: QuestionRepository;
let userRepository: UserRepository;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
CreateQuestionUseCase,
{
provide: QuestionRepository,
useClass: QuestionRepositoryMock,
},
{
provide: UserRepository,
useClass: UserRepositoryMock,
},
],
}).compile();

createQuestionUseCase = module.get<CreateQuestionUseCase>(CreateQuestionUseCase);
questionRepository = module.get<QuestionRepository>(QuestionRepository);
userRepository = module.get<UserRepository>(UserRepository);
});

it('should be defined', () => {
expect(createQuestionUseCase).toBeDefined();
});

it('should create a question when the author is found', async () => {
const createQuestionDto: CreateQuestionDto = {
content: 'What is your favorite color?',
authorId: 'fsdfsd-sdfsdfsd-sdfsdfsd-sdfsdf',
};

const question: Question = {
id: 'aaaaa-sdfsdfsd-sdfsdfsd-bbbbb',
content: createQuestionDto.content,
authorId: createQuestionDto.authorId,
createdAt: new Date(),
updatedAt: new Date(),
};

const user: Partial<User> = {
id: 'fsdfsd-sdfsdfsd-sdfsdfsd-sdfsdf',
username: 'test',
};

userRepository.findById = jest.fn().mockResolvedValue(user);
questionRepository.create = jest.fn().mockResolvedValue(question);

const result = await createQuestionUseCase.execute(createQuestionDto);

expect(result).toEqual(question);
expect(userRepository.findById).toHaveBeenCalledWith(createQuestionDto.authorId);
expect(questionRepository.create).toHaveBeenCalledWith({
content: createQuestionDto.content,
author: {
connect: {
id: createQuestionDto.authorId
}
}
});
});

it('should throw a not found exception when the author is not found', async () => {
const createQuestionDto: CreateQuestionDto = {
content: 'What is your favorite color?',
authorId: 'fsdfsd-sdfsdfsd-sdfsdfsd-sdfsdf',
};
userRepository.findById = jest.fn().mockResolvedValue(null);

await expect(createQuestionUseCase.execute(createQuestionDto)).rejects.toThrow('Author not found');

expect(userRepository.findById).toHaveBeenCalledWith(createQuestionDto.authorId);
});

it('should throw a bad request exception when it was not possible to register', async () => {
const createQuestionDto: CreateQuestionDto = {
content: 'What is your favorite color?',
authorId: 'fsdfsd-sdfsdfsd-sdfsdfsd-sdfsdf',
};

const user: Partial<User> = {
id: 'fsdfsd-sdfsdfsd-sdfsdfsd-sdfsdf',
username: 'test',
};

userRepository.findById = jest.fn().mockResolvedValue(user);
questionRepository.create = jest.fn().mockRejectedValue(new Error());

await expect(createQuestionUseCase.execute(createQuestionDto)).rejects.toThrow('Was not possible to register');

expect(userRepository.findById).toHaveBeenCalledWith(createQuestionDto.authorId);
expect(questionRepository.create).toHaveBeenCalledWith({
content: createQuestionDto.content,
author: {
connect: {
id: createQuestionDto.authorId
}
}
});
});
});
34 changes: 34 additions & 0 deletions src/modules/question/use-case/create-question.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

import { QuestionRepository, UserRepository } from '@app/common';
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { CreateQuestionDto } from '../dto/create-question.dto';

@Injectable()
export class CreateQuestionUseCase {
constructor(
private readonly questionRepository: QuestionRepository,
private readonly userRepository: UserRepository
) { }

async execute(createQuestionDto: CreateQuestionDto) {
const user = await this.userRepository.findById(createQuestionDto.authorId);

if (!user) {
throw new NotFoundException('Author not found');
}

try {
const question = await this.questionRepository.create({
content: createQuestionDto.content,
author: {
connect: {
id: user.id
}
}
});
return question;
} catch (e) {
throw new BadRequestException('Was not possible to register');
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { UsersModule } from '../users.module';
import { UsersModule } from '../user.module';
import { DatabaseModule, PrismaService } from '@app/common';
import { randomUUID } from 'node:crypto'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { UsersModule } from '../users.module';
import { UsersModule } from '../user.module';
import { DatabaseModule, PrismaService } from '@app/common';
import { randomUUID } from 'node:crypto'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { UsersModule } from '../users.module';
import { UsersModule } from '../user.module';
import { DatabaseModule, PrismaService } from '@app/common';
import { randomUUID } from 'node:crypto'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { UsersModule } from '../users.module';
import { UsersModule } from '../user.module';
import { DatabaseModule, PrismaService } from '@app/common';
import { randomUUID } from 'node:crypto'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { UsersModule } from '../users.module';
import { UsersModule } from '../user.module';
import { DatabaseModule, PrismaService } from '@app/common';
import { randomUUID } from 'node:crypto'

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ import { UpdateUserController } from './controllers/update-user.controller';
providers: [CreateUserUseCase, GetUserByIdUseCase, GetManyUsersUseCase, DeleteUserUseCase, UpdateUserUseCase],
exports: [],
})
export class UsersModule { }
export class UserModule { }

0 comments on commit 5583737

Please sign in to comment.