Commit a2d11356 authored by Robbie Antenesse's avatar Robbie Antenesse

Add shelf api route with create action

parent cd4e628e
......@@ -4,6 +4,24 @@ class ShelfController {
this.itemModel = shelfItemModel;
}
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;
}
async createDefaultShelves (user) {
try {
const defaultShelvesCreated = await this.model.bulkCreate([
......@@ -43,6 +61,18 @@ class ShelfController {
}
}
}
async createShelf (user, name) {
try {
return await user.addShelf({
name,
});
} catch(error) {
return {
error,
}
}
}
async getLastUpdatedTimestamp (shelf) {
const lastEditedItem = await this.itemModel.findOne({
......
......@@ -91,6 +91,7 @@ fastify.register(require('./i18n'));
fastify.register(require('./routes/public'));
fastify.register(require('./routes/books'));
fastify.register(require('./routes/account'));
fastify.register(require('./routes/shelf'));
fastify.register(require('./routes/search'));
// Start the server
......
const fs = require('fs');
const path = require('path');
const ShelfController = require('../controllers/shelf');
async function routes(fastify, options) {
fastify.get('/api/shelf/test', async (request, reply) => {
return false;
});
fastify.post('/api/shelf/create', async (request, reply) => {
if (!request.isLoggedInUser) {
return reply.code(400).send({
error: true,
message: 'api.not_logged_in',
});
}
if (typeof request.body.shelfName === 'undefined') {
return reply.code(400).send({
error: true,
message: 'api.shelf.create.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.createShelf(request.user, request.body.shelfName);
if (typeof newShelf.error !== 'undefined' && newShelf.error !== false) {
newShelf.message = 'api.shelf.create.fail';
return reply.code(400).send(newShelf);
}
return reply.send({
error: false,
message: 'api.shelf.create.success',
});
});
}
module.exports = routes;
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment