Create addShelfItem and endpoint

This commit is contained in:
Robbie Antenesse 2020-02-08 12:39:43 -07:00
parent f16aa470d8
commit 554fd3cf01
2 changed files with 77 additions and 0 deletions

View File

@ -248,6 +248,32 @@ class ShelfController {
return shelfData; 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; module.exports = ShelfController;

View File

@ -165,6 +165,57 @@ async function routes(fastify, options) {
message: 'api.shelf.rename.success', 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; module.exports = routes;