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

Us06 pesquisa de livro #5

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersModule } from './users/users.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';
import { BooksModule } from './books/books.module';
import typeormConfig from './database/config';

@Module({
Expand All @@ -18,6 +19,7 @@ import typeormConfig from './database/config';
}),
UsersModule,
AuthModule,
BooksModule
],
controllers: [],
providers: [],
Expand Down
13 changes: 13 additions & 0 deletions src/books/books.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Controller, Get, Query } from '@nestjs/common';
import { BooksService } from './books.service';
import { SearchBooksDto } from './dtos/searchBooks.dto';

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

@Get('search')
async searchBooks(@Query() searchParams: SearchBooksDto) {
return this.booksService.searchBooks(searchParams);
}
}
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 {}
59 changes: 59 additions & 0 deletions src/books/books.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Book } from '../database/entities/book.entity';
import { SearchBooksDto } from './dtos/searchBooks.dto';

@Injectable()
export class BooksService {
constructor(
@InjectRepository(Book)
private booksRepository: Repository<Book>,
) { }

async searchBooks(searchParams: SearchBooksDto) {
let { title, author, theme, page, limit } = searchParams;

page = parseInt(page as any, 10) || 1;
limit = parseInt(limit as any, 10) || 10;
const offset = (page - 1) * limit;

const filters: any = {};
if (title) filters.title = title;
if (author) filters.author = author;
if (theme) filters.theme = theme;

try {
const [books, totalBooks] = await this.booksRepository.findAndCount({
where: filters,
skip: offset,
take: limit,
order:{
averageRating : 'DESC',
title: 'ASC',
}
});

const totalPages = Math.ceil(totalBooks / limit);

if (books.length === 0) {
return {
message: 'Nenhum livro encontrado para a pesquisa realizada. Tente outros termos.',
totalPages: 0,
currentPage: page,
results: [],
};
}

return {
message: 'Livros encontrados com sucesso!',
totalPages,
currentPage: page,
results: books,
};
} catch (error) {
console.error(error);
throw new Error('Erro ao realizar a busca no banco de dados');
}
}
}
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;
}
41 changes: 41 additions & 0 deletions src/database/entities/book.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { HttpStatus } from '@nestjs/common';
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';

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

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

@Column()
title: string;

@Column()
author: string;

@Column()
theme: 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({
type: "enum",
enum: Status,
default: Status.AVAILABLE,
})
role: Status;
}
Loading