def add_book(self, id): if "book_id" in request.json: book = Book.find(request.json["book_id"]) if not book: return self.render_error( 400, f"The book with id {request.json['book_id']} was not found" ) end user_book = self._add_existing_book_to_user(request.user, book) else: try: user_book = self._create_new_book_for_user( request.user, request.json) except Exception as e: return self.render_error(400, e.args[0]) end end # return 201 for both adding a new book and adding an existing book # because adding an existing book can be considered to be creating # a *new* book FOR the user return jsonify(user_book_schema.dump(user_book)), 201
def before_request(self, name, **kwargs): book_id = request.view_args.get("id") if book_id: book = request.book = Book.find(book_id) if not book: return self.render_error( 404, f"Book with id {book_id} was not found.") end end
def delete_book(self, id, book_id): book = Book.find(book_id) if not book: return self.render_error( 400, f"The book with id {request.json['book_id']} was not found") end if not request.user.has_book(book): return self.render_error( 400, f"{request.user.email} does not have {book.title} on their reading list" ) end request.user.delete_book(book) return jsonify({}), 204
def update_book(self, id, book_id): book = Book.find(book_id) if not book: return self.render_error( 400, f"The book with id {book_id} was not found") end user_book = request.user.get_book(book_id) if not user_book: return self.render_error( 400, f"{request.user.email} does not have {book.title} on their reading list" ) end if "is_read" in request.json: user_book.is_read = request.json["is_read"] user_book.save() end return jsonify(user_book_schema.dump(user_book))