Skip to content

Commit

Permalink
Merge pull request #32 from danial117/derver_dev_26
Browse files Browse the repository at this point in the history
server_dev_
  • Loading branch information
danial117 committed Sep 7, 2024
2 parents c9eab1a + 2e596a2 commit 23ec3f8
Show file tree
Hide file tree
Showing 34 changed files with 2,344 additions and 716 deletions.
188 changes: 188 additions & 0 deletions controllers/CMS.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import CMSModel from "../models/CMSModel.js";
import {fileURLToPath} from 'url'
import path from "path";
import fs from 'fs'
import CustomError from "../utils/ErrorClass.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);


export const Get_CMS_Data=async(req,res,next)=>{

try{
const filter = JSON.parse(req.query.filter || '{}');
const range = JSON.parse(req.query.range || '[0, 10]');
const sort = JSON.parse(req.query.sort || '["createdAt", "ASC"]');

// Convert the sort array to an object for MongoDB
const sortObject = {};
sortObject[sort[0]] = sort[1] === 'DESC' ? -1 : 1;

// Extract pagination parameters
const skip = range[0];
const limit = range[1] - range[0] + 1;

// Build the query based on filter
const query = {};
if (filter) {
for (const key in filter) {
if (filter.hasOwnProperty(key)) {
// Check if the value is a number or a string
if (!isNaN(filter[key])) {
query[key] = filter[key]; // Direct match for numeric fields
} else {
query[key] = { $regex: new RegExp(filter[key], 'i') }; // Case-insensitive search for string fields
}
}
}
}




const CMS_Data = await CMSModel.find({});
const totalDocuments = await CMSModel.countDocuments(query);


const modified_CMS_Data = CMS_Data.map(data => {
const dataObject = data.toObject(); // Convert Mongoose document to plain JavaScript object
dataObject.id = dataObject._id;
delete dataObject._id;
return dataObject;
});

res.set({
'Content-Range': `orders ${range[0]}-${range[1]}/${totalDocuments}`,
'X-Total-Count': totalDocuments,
});

res.status(200).json(modified_CMS_Data);



}catch(err){

next(new CustomError(err.message, 500));
}
}













export const Create_CMS_Data=async(req,res,next)=>{

try{
const data=req.body;
const {id}=req.params
const files=req.files

const CMS_Dir=path.join(__dirname, '../public/CMS');



if(files){
files.forEach((file)=>{
data[file.fieldname]=file.filename;
const newPath = path.join(CMS_Dir, file.filename);

fs.rename(file.path,newPath,(err)=>{
if(err){

fs.unlinkSync(file.path);
}

})
})


}



const CMS_Data=await CMSModel.findById(id);

if(files.length>0){
files.forEach((file)=>{
const prevfile= CMS_Data[file.fieldname]
const delFile= path.join(CMS_Dir,prevfile)

fs.unlinkSync(delFile)


})

}


// Overwrite product fields with the fields from req.body
Object.keys(data).forEach(key => {
CMS_Data[key] = data[key];
});

// Save the updated product
const updated_CMS = await CMS_Data.save();



const modified_CMS = updated_CMS.toObject(); // Convert Mongoose document to plain JavaScript object
modified_CMS.id = modified_CMS._id;
delete modified_CMS._id;


res.status(200).json(modified_CMS)





}
catch(err){
next(new CustomError(err.message, 500));

}
}







export const AdminGetCMS=async(req,res,next)=>{

try{

const {id}=req.params;

const CMS=await CMSModel.findById(id);

const modifiedData = CMS.toObject(); // Convert Mongoose document to plain JavaScript object
modifiedData.id = modifiedData._id;
delete modifiedData._id;


res.status(200).json(modifiedData)





}catch(err){

next(new CustomError(err.message, 500));
}
}





55 changes: 33 additions & 22 deletions controllers/address.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import Address from '../models/AddressModel.js';
import CustomError from '../utils/ErrorClass.js';

// Controller function to create a new address
export const createAddress = async (req, res) => {
export const createAddress = async (req, res,next) => {
try {
// Assuming req.user is populated with user data by authMiddleware
const { userId } = req.user;
Expand All @@ -12,7 +13,7 @@ export const createAddress = async (req, res) => {
}

// Check if the user already has an address
let address = await Address.findOne({ user: userId });
let address = await Address.findOne({ user: userId }).select('email firstname lastname streetAddress state stateCode city zip');

if (address) {
// Update existing address
Expand Down Expand Up @@ -42,19 +43,25 @@ export const createAddress = async (req, res) => {
}

const savedAddress = await address.save();
const addressObject = savedAddress.toObject();
// Delete the 'user' property
delete addressObject.user;

res.status(201).json(savedAddress);
} catch (error) {
console.error('Error creating or updating address:', error);
res.status(500).json({ error: 'Internal server error' });

res.status(201).json(addressObject);
} catch (err) {


next(new CustomError(err.message, 500));

}
};




// Controller function to delete a user's address
export const deleteAddress = async (req, res) => {
export const deleteAddress = async (req, res,next) => {
try {
// Assuming req.user is populated with user data by authMiddleware
const { userId } = req.user;
Expand All @@ -73,9 +80,10 @@ export const deleteAddress = async (req, res) => {
}

res.status(200).json({ message: 'Address deleted successfully' });
} catch (error) {
console.error('Error deleting address:', error);
res.status(500).json({ error: 'Internal server error' });
} catch (err) {

next(new CustomError(err.message, 500));

}
};

Expand All @@ -84,22 +92,24 @@ export const deleteAddress = async (req, res) => {



export const getUserAddresses = async (req, res) => {
export const getUserAddresses = async (req, res,next) => {
try {
// Assuming req.user is populated with user data by authMiddleware
const { userId } = req.user;

// Find all addresses for the user
const addresses = await Address.findOne({ user: userId });
console.log(userId, addresses)
const addresses = await Address.findOne({ user: userId }).select('email firstName lastName streetAddress state stateCode city zip');

if (!addresses || addresses.length === 0) {
return res.status(404).json({ error: 'No addresses found for user' });
}

res.status(200).json(addresses);
} catch (error) {
console.error('Error retrieving addresses:', error);
res.status(500).json({ error: 'Internal server error' });
} catch (err) {


next(new CustomError(err.message, 500));

}
};

Expand All @@ -112,7 +122,7 @@ export const deleteAddress = async (req, res) => {



export const GetAdminUserAddresses = async (req, res) => {
export const GetAdminUserAddresses = async (req, res,next) => {
try {
// Extract filter, range, and sort parameters from the query
const filter = JSON.parse(req.query.filter || '{}');
Expand Down Expand Up @@ -142,8 +152,7 @@ export const deleteAddress = async (req, res) => {
}
}

console.log(query)
// Find orders based on the filter, sort, skip, and limit

const addresses = await Address.find(query).sort(sortObject).skip(skip).limit(limit);
const totalAddresses = await Address.countDocuments(query);

Expand All @@ -161,8 +170,10 @@ export const deleteAddress = async (req, res) => {
});

res.status(200).json(modifiedAddresses);
} catch (error) {
console.log(error);
res.status(500).json('Internal Server Error');
} catch (err) {


next(new CustomError(err.message, 500));

}
};
Loading

0 comments on commit 23ec3f8

Please sign in to comment.