Update shelf rename endpoint

This commit is contained in:
Robbie Antenesse 2020-02-08 12:39:10 -07:00
parent 7d20609cdf
commit f16aa470d8
2 changed files with 34 additions and 18 deletions

View File

@ -1,9 +1,17 @@
const fetch = require('node-fetch');
class ShelfController {
constructor (sequelizeModels) {
this.model = sequelizeModels.Shelf;
this.itemModel = sequelizeModels.ShelfItem;
constructor (sequelizeModels, language) { // Language needs to be passed with every request involving books.
this.models = sequelizeModels;
this.lang = language;
}
static userOwnsShelf(user, shelf) {
return typeof user !== 'undefined' && user.id === shelf.userId;
}
static shelfCanBeModified(shelf) {
return shelf.isDeletable === true;
}
static newShelfNameIsValid (name, existingNames = []) {
@ -32,7 +40,7 @@ class ShelfController {
async createDefaultShelves (user) {
try {
const defaultShelvesCreated = await this.model.bulkCreate([
const defaultShelvesCreated = await this.models.Shelf.bulkCreate([
{
userId: user.id,
name: 'Reading',
@ -82,17 +90,9 @@ class ShelfController {
}
}
async renameShelf (userId, id, name) {
async renameShelf (user, shelf, name) {
try {
return await this.model.update({
name,
}, {
where: {
id,
userId,
isDeletable: true, // You can only rename shelves not created by the system
}
});
return await shelf.update({ name });
} catch(error) {
return {
error,
@ -186,10 +186,10 @@ class ShelfController {
return shelf;
}
async userCanViewShelf (user, shelf) {
// This needs work when permissions are added.
const userOwnsShelf = typeof user !== 'undefined' && user.id === shelf.userId;
const userOwnsShelf = ShelfController.userOwnsShelf(user, shelf);
console.log('owned?', userOwnsShelf);
console.log('isPublic?', shelf.isPublic);
return userOwnsShelf || shelf.isPublic;

View File

@ -104,7 +104,7 @@ async function routes(fastify, options) {
fastify.post('/api/shelf/rename', async (request, reply) => {
if (!request.isLoggedInUser) {
return reply.code(400).send({
return reply.code(401).send({
error: true,
message: 'api.not_logged_in',
});
@ -136,9 +136,25 @@ async function routes(fastify, options) {
return reply.code(400).send(shelfNameIsValid);
}
const shelf = await fastify.models.Shelf.findByPk(request.body.shelfId);
if (!ShelfController.userOwnsShelf(request.user, shelf)) {
return reply.code(403).send({
error: true,
message: 'api.shelf.not_owner',
});
}
if (!ShelfController.shelfCanBeModified(shelf)) {
return reply.code(403).send({
error: true,
message: 'api.shelf.not_editable',
});
}
const shelfController = new ShelfController(fastify.models);
const newShelf = shelfController.renameShelf(request.user, request.body.shelfId, request.body.shelfName);
const newShelf = shelfController.renameShelf(request.user, shelf, request.body.shelfName);
if (typeof newShelf.error !== 'undefined' && newShelf.error !== false) {
newShelf.message = 'api.shelf.rename.fail';
return reply.code(400).send(newShelf);