/* * Controller base actions * * This module contains base actions that follow * a template for CRUD operations on a DB and (optionally) * do custom things afterward to return a response. */ const validation = require(`../../validation`); const db = require(`../../db`); const createAction = async (req, res, config) => { validation.validateOrThrow(config.validationSchema, req.body); const key = config.getObjectKey(); let existingObject = await db.getByKey(key); if (existingObject) { throw customError( `An object with key "${key}" already exists in the database.`, 400 ); } const dbObject = config.buildDbObject(req.body); await db.put(config.dbKind, dbObject); const createdObject = await db.getByKey(key); const responseBody = config.buildResponseBody(createdObject); res.json(responseBody); }; const getByKeyAction = async (req, res, config) => { validation.validateOrThrow(config.validationSchema, req.body); const key = config.getObjectKey(); let existingObject = await db.getByKey(key); if (!existingObject) { return res .status(404) .send({ error: config.notFoundMessage }); } const responseBody = config.buildResponseBody(existingObject); res.json(responseBody); }; /** * Build a custom error * @param {string} message Error message * @param {number} code Error code, should be HTTP status code */ const customError = (message = "An error occurred.", code = 500) => { const error = new Error(message); error.code = code; return error; }; module.exports = { createAction, getByKeyAction, };