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

Us05 empresta livro #16

Open
wants to merge 11 commits into
base: us05_empresta_livro
Choose a base branch
from
6 changes: 5 additions & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
MIT License

Copyright (c) 2025 EPS/MDS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SOFTWARE.

10 changes: 10 additions & 0 deletions listenv.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
DB_PORT=5432
DB_HOST=localhost
DB_USER=afonso
DB_PASSWORD=afonso
DB_NAME=test
ENVIRONMENT=dev
MAIL_HOST=
MAIL_USERNAME=
MAIL_PASSWORD=
APP_URL=http://localhost:3000
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { UsersModule } from './users/users.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';
import typeormConfig from './database/config';
import { BooksModule } from './books/books.module';

@Module({
imports: [
Expand All @@ -18,6 +19,7 @@ import typeormConfig from './database/config';
}),
UsersModule,
AuthModule,
BooksModule,
],
controllers: [],
providers: [],
Expand Down
32 changes: 32 additions & 0 deletions src/books/books.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Controller, Get, Param, Query, Put, Body } from '@nestjs/common';
import { BooksService } from './books.service';
import { SearchBooksDto } from './dtos/searchBooks.dto';
import { BorrowBooksDto } from './dtos/borrowBooks.dto';
import { UpdateBookStatusDto } from './dtos/updateBookStatus.dto'; // Certifique-se de importar esse DTO

@Controller('books')
export class BooksController {
constructor(private readonly booksService: BooksService) {}

@Get('search')
async searchBooks(@Query() searchParams: SearchBooksDto) {
return this.booksService.searchBooks(searchParams);
}

@Get(':id')
async getBookById(@Param('id') id: string): Promise<BorrowBooksDto> {
try {
return await this.booksService.getBookById(id);
} catch (error) {
throw error;
}
}

@Put(':id/status')
async updateBookStatus(
@Param('id') id: string,
@Body() updateBookStatusDto: UpdateBookStatusDto,
) {
return this.booksService.updateBookStatus(id, updateBookStatusDto);
}
}
24 changes: 24 additions & 0 deletions src/books/books.mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export const booksMock = [
{
id: 1,
title: 'Curupira, O guardião da floresta',
author: 'Saci-Pererê',
rating: 4.5,
description: 'Descrição do livro',
coverImage: '/curupira.jpeg',
status: 'Available',
userId: '',
date: '',
},
{
id: 2,
title: 'O boto cor de rosa',
author: 'Mula-sem-cabeça',
rating: 2.5,
description: 'Descrição do livro',
coverImage: '/boto.jpeg',
status: 'Available',
userId: '',
date: '',
},
];
12 changes: 12 additions & 0 deletions src/books/books.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { BooksController } from './books.controller';
import { BooksService } from './books.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Book } from '../database/entities/book.entity';

@Module({
imports: [TypeOrmModule.forFeature([Book])],
controllers: [BooksController],
providers: [BooksService],
})
export class BooksModule {}
48 changes: 48 additions & 0 deletions src/books/books.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Test, TestingModule } from '@nestjs/testing';
import { BooksService } from './books.service';
import { NotFoundException } from '@nestjs/common';
import { isString } from 'class-validator';

describe('BooksService', () => {
let booksService: BooksService;

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

booksService = module.get<BooksService>(BooksService);
});

it('deve buscar um livro por ID existente', async () => {
const result = await booksService.getBookById('1');
expect(result).toBeDefined();
expect(result.id).toBe(1);
});

it('deve lançar erro ao buscar um livro por ID inexistente', async () => {
await expect(booksService.getBookById('999')).rejects.toThrow(
NotFoundException,
);
});

it('deve atualizar o status de um livro existente', async () => {
const updatedBook = await booksService.updateBookStatus('1', {
status: 'NotAvailable',
userId: '',
date: '',
});
expect(updatedBook.status).toBe('NotAvailable');
});

it('deve lançar erro ao tentar atualizar o status de um livro inexistente', async () => {
await expect(
booksService.updateBookStatus('999', {
status: 'NotAvailable',
userId: '',
date: '',

}),
).rejects.toThrow(NotFoundException);
});
});
49 changes: 49 additions & 0 deletions src/books/books.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { BorrowBooksDto } from './dtos/borrowBooks.dto';
import { SearchBooksDto } from './dtos/searchBooks.dto';
import { UpdateBookStatusDto } from './dtos/updateBookStatus.dto';
import { booksMock } from './books.mock';

@Injectable()
export class BooksService {
private books = booksMock;

async searchBooks(searchParams: SearchBooksDto) {
return this.books.filter(
(book) =>
(searchParams.title ? book.title.includes(searchParams.title) : true) &&
(searchParams.author
? book.author.includes(searchParams.author)
: true),
);
}

async getBookById(id: string): Promise<BorrowBooksDto> {
const book = this.books.find((book) => book.id === Number(id));
if (!book) {
throw new NotFoundException('Livro não encontrado');
}
return book;
}

async updateBookStatus(
id: string,
updateBookStatusDto: UpdateBookStatusDto,
): Promise<BorrowBooksDto> {
const bookIndex = this.books.findIndex((book) => book.id === Number(id));

if (bookIndex === -1) {
throw new NotFoundException('Livro não encontrado');
}


this.books[bookIndex] = {
...this.books[bookIndex],
status: updateBookStatusDto.status,
userId: updateBookStatusDto.userId,
date: new Date().toISOString(),
};

return this.books[bookIndex];
}
}
9 changes: 9 additions & 0 deletions src/books/dtos/borrowBooks.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export class BorrowBooksDto {
id: number;
title: string;
author: string;
rating: number;
description: string;
coverImage: string;
status: string;
}
25 changes: 25 additions & 0 deletions src/books/dtos/searchBooks.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { IsOptional, IsString, IsInt, Min } from 'class-validator';

export class SearchBooksDto {
@IsOptional()
@IsString()
title?: string;

@IsOptional()
@IsString()
author?: string;

@IsOptional()
@IsString()
theme?: string;

@IsOptional()
@IsInt()
@Min(1)
page: number = 1;

@IsOptional()
@IsInt()
@Min(1)
limit: number = 20;
}
5 changes: 5 additions & 0 deletions src/books/dtos/updateBookStatus.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export class UpdateBookStatusDto {
status: string;
userId: string;
date: string;
}
43 changes: 43 additions & 0 deletions src/database/entities/book.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

export enum Status {
AVAILABLE = 'available',
NOTAVAILABLE = 'notAvailable',
}

@Entity()
export class Book {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column()
title: string;

@Column()
coverImage: string;

@Column()
author: string;

@Column()
theme: string;

@Column()
description: string;

@Column({ type: 'decimal', precision: 2, scale: 1, default: 0 })
averageRating: number; // Média de avaliação dos usuários (0.0 a 5.0)

@Column({ nullable: true })
coverUrl: string; // URL da capa do livro

@Column({ nullable: true })
borrowedBy: string;

@Column({
type: 'enum',
enum: Status,
default: Status.AVAILABLE,
})
role: Status;
}
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
app.enableCors();
await app.listen(process.env.PORT || 3000);
await app.listen(process.env.PORT || 3001);
}
bootstrap();
Loading