Add rename shelf API endpoint

This commit is contained in:
Robbie Antenesse 2019-12-11 13:15:55 -07:00
parent cdcaef11c1
commit 237198cd47
2 changed files with 66 additions and 0 deletions

View File

@ -73,6 +73,24 @@ class ShelfController {
} }
} }
} }
async renameShelf (userId, id, name) {
try {
return await this.model.update({
name,
}, {
where: {
id,
userId,
isDeletable: true, // You can only rename shelves not created by the system
}
});
} catch(error) {
return {
error,
}
}
}
async getLastUpdatedTimestamp (shelf) { async getLastUpdatedTimestamp (shelf) {
const lastEditedItem = await this.itemModel.findOne({ const lastEditedItem = await this.itemModel.findOne({

View File

@ -47,6 +47,54 @@ async function routes(fastify, options) {
message: 'api.shelf.create.success', message: 'api.shelf.create.success',
}); });
}); });
fastify.post('/api/shelf/rename', async (request, reply) => {
if (!request.isLoggedInUser) {
return reply.code(400).send({
error: true,
message: 'api.not_logged_in',
});
}
if (typeof request.body.shelfId === 'undefined') {
return reply.code(400).send({
error: true,
message: 'api.shelf.rename.missing_id',
});
}
if (typeof request.body.shelfName === 'undefined') {
return reply.code(400).send({
error: true,
message: 'api.shelf.rename.missing_name',
});
}
request.body.shelfName = request.body.shelfName.trim();
const userShelves = await request.user.getShelves({
attributes: ['name'],
});
const shelfNameIsValid = ShelfController.newShelfNameIsValid(
request.body.shelfName,
userShelves.map(shelf => shelf.name)
);
if (shelfNameIsValid !== true) {
return reply.code(400).send(shelfNameIsValid);
}
const shelf = new ShelfController(fastify.models.Shelf, fastify.models.ShelfItem);
const newShelf = shelf.renameShelf(request.user, request.body.shelfId, request.body.shelfName);
if (typeof newShelf.error !== 'undefined' && newShelf.error !== false) {
newShelf.message = 'api.shelf.rename.fail';
return reply.code(400).send(newShelf);
}
return reply.send({
error: false,
message: 'api.shelf.rename.success',
});
});
} }
module.exports = routes; module.exports = routes;