Skip to content
Open
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
55 changes: 13 additions & 42 deletions src/routes/books.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Router } from "express"
import { BookService } from "../services/book-service.ts"
import { createBookSchema } from "../schema/book-schema.ts"
import { z } from "zod"

const router = Router()
const bookService = new BookService()
Expand All @@ -22,51 +24,20 @@ router.get("/:id", (req, res) => {
})

router.post("/", (req, res) => {
const { title, author, genre, description, pages, imageURL } = req.body
try {
const validatedData = createBookSchema.parse(req.body)

if (!title) {
res.status(400).json({
error: "Preencha todos os campos!"
})
return
}

if (!genre) {
res.status(400).json({
error: "O gênero do livro é obrigatório."
})
return
}

if (!description) {
res.status(400).json({
error: "A descrição do livro é obrigatório."
})
return
}
const newBook = bookService.create(validatedData);

if (!pages) {
res.status(400).json({
error: "O número de páginas do livro é obrigatório."
})
return
res.status(201).json(newBook)
} catch (error) {
if (error instanceof z.ZodError) {
res.status(400).json({
error: error.issues.map((err) => err.message).join("; ")
})
return
}
}

if (!imageURL) {
res.status(400).json({
error: "A imagem do livro é obrigatória."
})
return
}

const newBook = bookService.create({
title,
author,
genre,
description,
imageURL
})
res.status(201).json(newBook)
})

router.put("/:id", (req, res) => {
Expand Down
35 changes: 35 additions & 0 deletions src/schema/book-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { z } from "zod"

export const createBookSchema = z.object({
title: z.string({
message: "O título é obrigatório"
})
.min(1, "O título não pode estar vazio"),
author: z.string({
message: "O autor é obrigatório"
})
.min(1, "O autor não pode estar vazio"),
description: z.string({
message: "A descrição é obrigatória"
})
.max(500, "A descrição deve ter no máximo 500 caracteres")
.min(1, "A descrição não pode estar vazia"),
genre: z.string({
message: "O gênero é obrigatório"
})
.transform((str) => str.split(",").map(g => g.trim()).filter(g => g.length > 0)),
pages: z.number({
message: "O número de páginas é obrigatório"
})
.positive("O número de páginas deve ser maior que zero")
.int("O número de páginas deve ser um número inteiro"),
imageURL: z.string({
message: "A URL da imagem é obrigatória"
})
.url("A URL da imagem não é inválida"),
})

export const updateBookSchema = createBookSchema.partial()

export type CreateBookInput = z.infer<typeof createBookSchema>
export type UpdateBookInput = z.infer<typeof updateBookSchema>
12 changes: 12 additions & 0 deletions src/schema/borrow-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { z } from "zod"

export const createBorrowSchema = z.object({
bookId: z.string({
error: "O ID do livro é obrigatório"
}),
studentName: z.string({
error: "O nome do estudante é obrigatório"
})
})

export type CreateBorrowInput = z.infer<typeof createBorrowSchema>
15 changes: 8 additions & 7 deletions src/services/book-service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto"
import { DatabaseRepository, IBook } from "../utils/db.ts"
import { CreateBookInput } from "../schema/book-schema.ts"

export class BookService {
public getAll(genre?: string): IBook[] {
Expand All @@ -17,17 +18,17 @@ export class BookService {
return databaseState.books.find(book => String(book.id) === id) || null
}

public create(bookData: Partial<IBook>): IBook {
public create(bookData: CreateBookInput): IBook {
const databaseState = DatabaseRepository.read()

const newBook: IBook = {
id: randomUUID(),
title: bookData.title!,
author: bookData.author!,
description: bookData.description!,
genre: bookData.genre!,
pages: bookData.pages!,
imageURL: bookData.imageURL!,
title: bookData.title,
author: bookData.author,
description: bookData.description || "",
genre: bookData.genre,
pages: bookData.pages,
imageURL: bookData.imageURL || "",
available: true
}

Expand Down
Loading