diff --git a/server/controllers/shelf.js b/server/controllers/shelf.js index 51a958e..1505db2 100644 --- a/server/controllers/shelf.js +++ b/server/controllers/shelf.js @@ -248,6 +248,32 @@ class ShelfController { return shelfData; } + + async addShelfItem(shelf, bookReferenceId, source = null) { + const bookReferenceController = new BookReferenceController(this.models, this.lang); + + let bookId = bookReferenceId; + if (source !== null) { + const bookReference = await bookReferenceController.createOrUpdateReference(source, bookId); + bookId = bookReference.id; + } + + if (shelf.ShelfItems.some(shelfItem => shelfItem.bookId === bookId)) { + return { + error: 'api.shelf.addItem.already_on_shelf', // This may need to change to account for editions later. + } + } + + const shelfItem = await shelf.addShelfItem({ bookId }).catch(err => err); + + if (!shelfItem) { + return { + error: shelfItem, + }; + } + + return shelfItem; + } } module.exports = ShelfController; \ No newline at end of file diff --git a/server/routes/shelf.js b/server/routes/shelf.js index 339f6f7..a53c099 100644 --- a/server/routes/shelf.js +++ b/server/routes/shelf.js @@ -165,6 +165,57 @@ async function routes(fastify, options) { message: 'api.shelf.rename.success', }); }); + + fastify.post('/api/shelf/addItem', async (request, reply) => { + if (!request.isLoggedInUser) { + return reply.code(401).send({ + error: true, + message: 'api.not_logged_in', + }); + } + + if (typeof request.body.shelfId === 'undefined') { + return reply.code(400).send({ + error: true, + message: 'api.shelf.addItem.missing_id', + }); + } + + if (typeof request.body.bookId === 'undefined') { + return reply.code(400).send({ + error: true, + message: 'api.shelf.addItem.missing_id', + }); + } + + const shelf = await request.user.getShelf({ + where: { id: request.body.shelfId }, + include: [ fastify.models.ShelfItem ], + }); + + if (!ShelfController.userOwnsShelf(request.user, shelf)) { + return reply.code(403).send({ + error: true, + message: 'api.shelf.not_owner', + }); + } + + const shelfController = new ShelfController(fastify.models, request.language); + + const shelfItem = await shelfController.addShelfItem(shelf, request.body.bookId, request.body.source); + + if (typeof shelfItem.error !== 'undefined') { + return reply.code(400).send({ + error: shelfItem.error, + message: 'api.shelf.addItem.could_not_add', + }); + } + + return reply.send({ + error: false, + message: 'api.shelf.addItem.success', + }); + }); } module.exports = routes; \ No newline at end of file