const Brand = require("../models/Brand"); const { checkValidations } = require("../plugins/HelperFunctions") const { body, validationResult } = require('express-validator') const { _sr } = require("../plugins/resServer") //@desc Create a brand //@route POST /api/brands/ //@access Private const createbrand = [ [ body('title').notEmpty().withMessage(_sr.fa.required.title), body('description').notEmpty().withMessage(_sr.fa.required.description), body('link').notEmpty().trim().isLowercase().withMessage(_sr.fa.required.field), body('logo').notEmpty().withMessage(_sr.fa.required.image), ], checkValidations(validationResult), async (req, res) => { const { title, link, description, logo } = req.body; const linkAvailable = await Brand.findOne({ link }); if (linkAvailable) { res.status(400); throw new Error(_sr.fa.duplicated.link); } const brand = await Brand.create({ title, link, description, logo, }); res.status(201).json(brand); } ] //@desc Get to all brands //@route GET /api/brands/ //@access Public const getbrands = async (req, res) => { const brand = await Brand.find(); res.status(200).json(brand); }; //@desc Get to brand by id //@route GET /api/brands/id/:id //@access Public const getbrand = async (req, res) => { const brand = await Brand.findById(req.params.id); if (!brand) { res.status(404) throw new Error(_sr.fa.not_found.item_id) } res.status(200).json(brand); }; //@desc Update a brand //@route Put /api/brands/:id //@access Private const updatebrand = [ [ body('title').notEmpty().withMessage(_sr.fa.required.title), body('description').notEmpty().withMessage(_sr.fa.required.description), body('link').notEmpty().trim().isLowercase().withMessage(_sr.fa.required.field), body('logo').notEmpty().withMessage(_sr.fa.required.image), ], checkValidations(validationResult), async (req, res) => { const { title, link, description, logo, native, ordering } = req.body; const brand = await Brand.findById(req.params.id); if (!brand) { res.status(404); throw new Error(_sr.fa.not_found.item_id); } const linkAvailable = await Brand.findOne({ link }); if (linkAvailable && linkAvailable.id != req.params.id) { res.status(400); throw new Error(_sr.fa.duplicated.link); } const updateBrand = await Brand.findByIdAndUpdate( req.params.id, { title, link, description, logo, native, ordering }, { new: true } ); res.status(201).json(updateBrand); } ] //@desc Delete a brand //@route DELETE /api/brands/:id //@access Private const deletebrand = async (req, res) => { const brand = await Brand.findById(req.params.id); if (!brand) { res.status(404); throw new Error(_sr.fa.not_found.item_id); } await brand.deleteOne(); res.status(201).json(brand); }; module.exports = { createbrand, getbrands, getbrand, updatebrand, deletebrand, };