Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 4x 4x 9x 9x 7x 7x 7x 32x 2x 30x 180x 2x 2x 2x 1x 1x 2x 2x 2x 1x 1x 1x 1x 2x 2x 1x 1x 1x 4x | const uuid = require("uuid")
const READING_STATUS = require("../constants/reading-status");
class BookService {
constructor(
bookRepository,
{ id, user, title, status, startDateReading, endDateReading }
) {
this.bookRepository = bookRepository;
this.book = {
id,
user,
title,
status,
startDateReading,
endDateReading,
}
}
getStatusRef() {
return READING_STATUS[this.book.status];
}
validateBody() {
const { title, fields } = this.getStatusRef();
fields.forEach((field) => {
if (!this.book[field]) {
throw new Error(
`The field "${field}" is required for registers with reading status "${title}"`
);
}
for (const BookField in this.book) {
if(!fields.includes(BookField) && this.book[BookField]) {
throw new Error(
`The field "${BookField}" should't be present for records with read status "${title}"`
);
}
}
});
}
async save() {
this.book.id = uuid.v4()
this.validateBody()
const newBookRegister = await this.bookRepository.save(this.book);
return newBookRegister
}
async update() {
this.validateBody()
const book = await this.bookRepository.find(this.book.id, "id")
if(!book?.id) {
throw new Error(`Book with id "${this.book.id}" Not Found!!`)
}
const { id, user, ...bookData} = this.book
const updatedBook = await this.bookRepository.update(this.book.id, {
user: book.user,
...bookData
})
return updatedBook
}
async delete() {
const bookExists = await this.bookRepository.find(this.book.id, "id")
if(!bookExists.id) {
throw new Error(`Book with id "${this.book.id}" Not Found!!`)
}
this.bookRepository.delete(this.book.id)
return
}
}
module.exports = BookService;
|