59 lines
1.7 KiB
JavaScript
59 lines
1.7 KiB
JavaScript
'use strict';
|
|
|
|
const { AppParamError, AppError } = require('../helpers/app_error');
|
|
|
|
const Product = require('../model/product'),
|
|
Job = require('../model/job'),
|
|
ObjectId = require('mongodb').ObjectId,
|
|
{ Errors } = require('../helpers/constants');
|
|
|
|
async function getProducts_get(req, res) {
|
|
const products = await Product.find({});
|
|
res.json(products);
|
|
}
|
|
|
|
async function createProduct_post(req, res) {
|
|
const _product = req.body;
|
|
delete _product._id;
|
|
const product = new Product(_product);
|
|
|
|
const savedProduct = await product.save();
|
|
res.json(savedProduct);
|
|
}
|
|
|
|
async function getProduct_get(req, res) {
|
|
const product = await Product.findById(req.params.product_id);
|
|
res.json(product);
|
|
}
|
|
|
|
async function updateProduct_put(req, res) {
|
|
const _product = req.body;
|
|
delete _product._id;
|
|
const product = await Product.findOneAndUpdate({ _id: req.params.product_id }, _product, { new: true, lean: true });
|
|
res.json(product);
|
|
}
|
|
|
|
async function deleteProduct(req, res) {
|
|
const _pid = req.params.product_id;
|
|
|
|
const jobs = await Job.find({ products: { $elemMatch: { 'product': ObjectId(_pid) } } }).limit(1);
|
|
if (jobs && jobs.length) AppError.throw(Errors.HAS_REFERENCE);
|
|
|
|
const product = await Product.deleteOne({ _id: _pid });
|
|
res.json(product);
|
|
}
|
|
|
|
async function search_post(req, res) {
|
|
const _options = {};
|
|
if (req.body.byUserId && ObjectId.isValid(req.body.byUserId))
|
|
_options.byPuid = ObjectId(req.body.byUserId);
|
|
else
|
|
AppParamError.throw();
|
|
|
|
const products = await Product.find(_options, null, { lean: true });
|
|
res.json(products || []);
|
|
}
|
|
|
|
module.exports = {
|
|
getProducts_get, createProduct_post, getProduct_get, updateProduct_put, deleteProduct, search_post
|
|
} |