2019-12-01 19:03:55 +01:00
|
|
|
class ShelfController {
|
2019-12-01 02:02:24 +01:00
|
|
|
constructor (shelfModel, shelfItemModel) {
|
|
|
|
this.model = shelfModel;
|
|
|
|
this.itemModel = shelfItemModel;
|
|
|
|
}
|
|
|
|
|
2019-12-01 23:31:34 +01:00
|
|
|
static newShelfNameIsValid (name, existingNames = []) {
|
|
|
|
if (name.length < 1) {
|
|
|
|
return {
|
|
|
|
error: true,
|
|
|
|
message: 'api.shelf.create.name_too_short',
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
if (existingNames.includes(name)) {
|
|
|
|
return {
|
|
|
|
error: true,
|
|
|
|
message: 'api.shelf.create.name_already_exists',
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-12-01 02:02:24 +01:00
|
|
|
async createDefaultShelves (user) {
|
|
|
|
try {
|
|
|
|
const defaultShelvesCreated = await this.model.bulkCreate([
|
|
|
|
{
|
|
|
|
userId: user.id,
|
|
|
|
name: 'Reading',
|
|
|
|
isDeletable: false,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
userId: user.id,
|
|
|
|
name: 'Want to Read',
|
|
|
|
isDeletable: false,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
userId: user.id,
|
|
|
|
name: 'Finished',
|
|
|
|
isDeletable: false,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
userId: user.id,
|
|
|
|
name: 'Did Not Finish',
|
|
|
|
isDeletable: false,
|
|
|
|
}
|
|
|
|
]);
|
|
|
|
|
|
|
|
if (defaultShelvesCreated.some(result => !result)) {
|
|
|
|
return {
|
|
|
|
error: true,
|
|
|
|
shelfResults: defaultShelvesCreated,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return defaultShelvesCreated;
|
|
|
|
} catch (error) {
|
|
|
|
return {
|
|
|
|
error,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-12-01 23:31:34 +01:00
|
|
|
|
|
|
|
async createShelf (user, name) {
|
|
|
|
try {
|
|
|
|
return await user.addShelf({
|
|
|
|
name,
|
|
|
|
});
|
|
|
|
} catch(error) {
|
|
|
|
return {
|
|
|
|
error,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-12-11 21:15:55 +01:00
|
|
|
|
|
|
|
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,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-12-01 02:02:24 +01:00
|
|
|
|
|
|
|
async getLastUpdatedTimestamp (shelf) {
|
2019-12-24 00:51:26 +01:00
|
|
|
const lastEditedItem = await shelf.getShelfItems({
|
2019-12-01 02:02:24 +01:00
|
|
|
attributes: ['updatedAt'],
|
|
|
|
order: [
|
|
|
|
[
|
|
|
|
'updatedAt',
|
|
|
|
'DESC'
|
|
|
|
],
|
|
|
|
],
|
2019-12-24 00:51:26 +01:00
|
|
|
limit: 1,
|
2019-12-01 02:02:24 +01:00
|
|
|
});
|
|
|
|
|
2019-12-24 00:51:26 +01:00
|
|
|
if (lastEditedItem.length > 0 && (lastEditedItem[0].updatedAt > shelf.updatedAt)) {
|
2019-12-01 02:02:24 +01:00
|
|
|
return lastEditedItem.updatedAt;
|
|
|
|
}
|
|
|
|
return shelf.updatedAt;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-01 19:03:55 +01:00
|
|
|
module.exports = ShelfController;
|