api/v1/days/controller.js

import get from "lodash/get"

import { prepQuery } from "./helpers"

import BaseController from "../../BaseController"
import DayModel from "./model"

/**
 * Controller for the @namespace /day
 *
 * @class DaysController
 * @extends {BaseController}
 */
class DaysController extends BaseController {
    constructor() {
        super()

        this.index = this.index.bind(this)
        this.show = this.show.bind(this)
    }

    /**
     * GET / Fetch the full day (collection of days)
     *
     * @memberof DaysController
     */
    async index(req, res) {
        const { success, unprocessableEntity } = this.codes
        const query = prepQuery(req.query)

        const day = new DayModel()
        const result = await day.find(query)
            .catch((error) => {
                res.status(unprocessableEntity).send({
                    success: "false",
                    message: "days_error",
                    error,
                })

                throw error
            })

        res.status(success).send({
            success: "true",
            message: "days_retrieved_successfully",
            days: get(result, "rows", []),
        })
    }

    /**
     * GET /:id Fetch specific day by identifier
     *
     * @param {int} id | Day identifier
     * @memberof DaysController
     */
    async show(req, res) {
        const { success, notFound, unprocessableEntity } = this.codes
        const { id } = req.params

        const day = new DayModel()
        const result = await day.find({ id })
            .catch((error) => {
                res.status(unprocessableEntity).send({
                    success: "false",
                    message: "day_error",
                    error,
                })

                throw error
            })

        day.set(get(result, "rows[0]"))

        if (day.error) {
            res.status(notFound).send({
                success: "false",
                message: "day_not_found",
                error: day.error,
            })

            return
        }

        res.status(success).send({
            success: "true",
            message: "day_retrieved_successfully",
            day: day.props,
        })
    }
}

export default DaysController