api/v1/categories/controller.js

import get from "lodash/get"

import BaseController from "../../BaseController"
import CategoryModel from "./model"

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

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

    /**
     * GET / Fetch all categories
     *
     * @memberof CategoriesController
     */
    async index(_, res) {
        const { success, unprocessableEntity } = this.codes

        const category = new CategoryModel()
        const result = await category.all()
            .catch((error) => {
                res.status(unprocessableEntity).send({
                    success: "false",
                    message: "categories_error",
                    error,
                })

                throw error
            })

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

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

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

                throw error
            })

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

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

            return
        }

        res.status(success).send({
            success: "true",
            message: "category_retrieved_successfully",
            category: category.props,
        })
    }
}

export default CategoriesController