144 lines
4.1 KiB
JavaScript

import dotenv from "dotenv";
import { partStockModel } from "../../schemas/partstock.schema.js";
import jwt from "jsonwebtoken";
import log4js from "log4js";
import mongoose from "mongoose";
dotenv.config();
const logger = log4js.getLogger("PartStocks");
logger.level = process.env.LOG_LEVEL;
export const listPartStocksRouteHandler = async (
req,
res,
page = 1,
limit = 25,
property = "",
filter = {},
) => {
try {
// Calculate the skip value based on the page number and limit
const skip = (page - 1) * limit;
let partStock;
let aggregateCommand = [];
if (filter != {}) {
// use filtering if present
aggregateCommand.push({ $match: filter });
}
if (property != "") {
aggregateCommand.push({ $group: { _id: `$${property}` } }); // group all same properties
aggregateCommand.push({ $project: { _id: 0, [property]: "$_id" } }); // rename _id to the property name
} else {
aggregateCommand.push({ $project: { image: 0, url: 0 } });
}
aggregateCommand.push({ $skip: skip });
aggregateCommand.push({ $limit: Number(limit) });
console.log(aggregateCommand);
partStock = await partStockModel.aggregate(aggregateCommand);
logger.trace(
`List of partStocks (Page ${page}, Limit ${limit}, Property ${property}):`,
partStock,
);
res.send(partStock);
} catch (error) {
logger.error("Error listing partStocks:", error);
res.status(500).send({ error: error });
}
};
export const getPartStockRouteHandler = async (req, res) => {
try {
// Get ID from params
const id = new mongoose.Types.ObjectId(req.params.id);
// Fetch the partStock with the given remote address
const partStock = await partStockModel.findOne({
_id: id,
});
if (!partStock) {
logger.warn(`PartStock not found with supplied id.`);
return res.status(404).send({ error: "Print job not found." });
}
logger.trace(`PartStock with ID: ${id}:`, partStock);
res.send(partStock);
} catch (error) {
logger.error("Error fetching PartStock:", error);
res.status(500).send({ error: error.message });
}
};
export const editPartStockRouteHandler = async (req, res) => {
try {
// Get ID from params
const id = new mongoose.Types.ObjectId(req.params.id);
// Fetch the partStock with the given remote address
const partStock = await partStockModel.findOne({ _id: id });
if (!partStock) {
// Error handling
logger.warn(`PartStock not found with supplied id.`);
return res.status(404).send({ error: "Print job not found." });
}
logger.trace(`PartStock with ID: ${id}:`, partStock);
try {
const updateData = {
updatedAt: new Date(),
contact: req.body.contact,
country: req.body.country,
name: req.body.name,
website: req.body.website,
phone: req.body.phone,
email: req.body.email,
};
const result = await partStockModel.updateOne(
{ _id: id },
{ $set: updateData },
);
if (result.nModified === 0) {
logger.error("No PartStock updated.");
res.status(500).send({ error: "No partStocks updated." });
}
} catch (updateError) {
logger.error("Error updating partStock:", updateError);
res.status(500).send({ error: updateError.message });
}
res.send("OK");
} catch (fetchError) {
logger.error("Error fetching partStock:", fetchError);
res.status(500).send({ error: fetchError.message });
}
};
export const newPartStockRouteHandler = async (req, res) => {
try {
let { ...newPartStock } = req.body;
newPartStock = {
...newPartStock,
createdAt: new Date(),
updatedAt: new Date(),
};
const result = await partStockModel.create(newPartStock);
if (result.nCreated === 0) {
logger.error("No partStock created.");
res.status(500).send({ error: "No partStock created." });
}
res.status(200).send({ status: "ok" });
} catch (updateError) {
logger.error("Error updating partStock:", updateError);
res.status(500).send({ error: updateError.message });
}
};