1
0
Fork 0
mirror of https://github.com/codex-team/codex.docs.git synced 2025-07-22 06:39:42 +02:00

Page model (#1)

* Initial database and page MVC

* Add mocha tests

* Add docs

* Add docs about nedb query options

* Add eslint and editorconfig + husky

* Improve precommit script

* Remove unnecessary dependencies
This commit is contained in:
George Berezhnoy 2018-08-17 13:58:44 +03:00 committed by GitHub
parent 2e717f6415
commit 7add63d90b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 4361 additions and 42 deletions

106
controllers/pages.js Normal file
View file

@ -0,0 +1,106 @@
const Model = require('../models/page');
/**
* @class Pages
* @classdesc Pages controller
*/
class Pages {
/**
* @static
* Fields required for page model creation
*
* @returns {['title', 'body']}
*/
static get REQUIRED_FIELDS() {
return ['title', 'body'];
}
/**
* @static
* Find and return page model with passed id
*
* @param {string} id - page id
* @returns {Promise<Page>}
*/
static async get(id) {
const page = await Model.get(id);
if (!page._id) {
throw new Error('Page with given id does not exist');
}
return page;
}
/**
* Return all pages
*
* @returns {Promise<Page[]>}
*/
static async getAll() {
return Model.getAll();
}
/**
* Create new page model and save it in the database
*
* @param {PageData} data
* @returns {Promise<Page>}
*/
static async insert(data) {
if (!Pages.validate(data)) {
throw new Error('Invalid request format');
}
const page = new Model(data);
return page.save();
}
/**
* Check PageData object for required fields
*
* @param {PageData} data
* @returns {boolean}
*/
static validate(data) {
return Pages.REQUIRED_FIELDS.every(field => typeof data[field] !== 'undefined');
}
/**
* Update page with given id in the database
*
* @param {string} id - page id
* @param {PageData} data
* @returns {Promise<Page>}
*/
static async update(id, data) {
const page = await Model.get(id);
if (!page._id) {
throw new Error('Page with given id does not exist');
}
page.data = data;
return page.save();
}
/**
* Remove page with given id from the database
*
* @param {string} id - page id
* @returns {Promise<Page>}
*/
static async remove(id) {
const page = await Model.get(id);
if (!page._id) {
throw new Error('Page with given id does not exist');
}
return page.destroy();
}
}
module.exports = Pages;