From d738b9061f59cb3cc850e3f013dbfd81a9006e20 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 23 Oct 2018 23:13:56 -0400 Subject: [PATCH] add book controller and route --- api/controllers/BooksController.js | 35 ++++++++++++++++++++++++++++++ api/models/Book.js | 31 ++++++++++++++++++++++++++ config/routes.js | 12 +++++++--- 3 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 api/controllers/BooksController.js create mode 100644 api/models/Book.js diff --git a/api/controllers/BooksController.js b/api/controllers/BooksController.js new file mode 100644 index 0000000..cade2c1 --- /dev/null +++ b/api/controllers/BooksController.js @@ -0,0 +1,35 @@ +/** + * BooksController + * + * @description :: Server-side actions for handling incoming requests. + * @help :: See https://sailsjs.com/docs/concepts/actions + */ + +module.exports = { + publish: async function (req, res) { + try { + const body = req.body + const host = req.hostname + let result + + if (!host) throw new Error('Missing hostname') + if (!body) throw new Error('Missing body') + + const bookExists = await Book.findOne(body) + + if (bookExists) { + throw new Error('Version already exists') + } else { + result = await Book.create(body) + } + + return res.json({ + ...result + }) + } catch (e) { + return res.status(400).json({ + error: e.message + }) + } + } +} diff --git a/api/models/Book.js b/api/models/Book.js new file mode 100644 index 0000000..940be66 --- /dev/null +++ b/api/models/Book.js @@ -0,0 +1,31 @@ +/** + * Book.js + * + * @description :: A model definition. Represents a database table/collection/etc. + * @docs :: https://sailsjs.com/docs/concepts/models-and-orm/models + */ + +module.exports = { + + attributes: { + + // ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦ ╦╔═╗╔═╗ + // ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗ + // ╩ ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝ + title: {type: 'string', required: true}, + author: {type: 'string'}, + isbn: {type: 'string'}, + version: {type: 'string'}, + + // ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗ + // ║╣ ║║║╠╩╗║╣ ║║╚═╗ + // ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝ + + + // ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗ + // ╠═╣╚═╗╚═╗║ ║║ ║╠═╣ ║ ║║ ║║║║╚═╗ + // ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝ + + }, + +} diff --git a/config/routes.js b/config/routes.js index 69bc6c6..5b79955 100644 --- a/config/routes.js +++ b/config/routes.js @@ -9,8 +9,6 @@ */ module.exports.routes = { - - // ╦ ╦╔═╗╔╗ ╔═╗╔═╗╔═╗╔═╗╔═╗ // ║║║║╣ ╠╩╗╠═╝╠═╣║ ╦║╣ ╚═╗ // ╚╩╝╚═╝╚═╝╩ ╩ ╩╚═╝╚═╝╚═╝ @@ -28,6 +26,10 @@ module.exports.routes = { view: 'pages/homepage' }, + 'GET /test': { + view: 'pages/test' + }, + /*************************************************************************** * * * More custom routes here... * @@ -44,6 +46,10 @@ module.exports.routes = { // ╠═╣╠═╝║ ║╣ ║║║ ║║╠═╝║ ║║║║║ ║ ╚═╗ // ╩ ╩╩ ╩ ╚═╝╝╚╝═╩╝╩ ╚═╝╩╝╚╝ ╩ ╚═╝ + 'POST /api/publish': { + controller: 'books', + action: 'publish' + }, // ╦ ╦╔═╗╔╗ ╦ ╦╔═╗╔═╗╦╔═╔═╗ @@ -56,4 +62,4 @@ module.exports.routes = { // ╩ ╩╩╚═╝╚═╝ -}; +}