Skip to content

Commit

Permalink
Created an API for Products
Browse files Browse the repository at this point in the history
  • Loading branch information
Nandita10062001 committed Oct 1, 2024
1 parent 89f36d5 commit a973bf6
Show file tree
Hide file tree
Showing 22 changed files with 2,074 additions and 2 deletions.
178 changes: 178 additions & 0 deletions controllers/productController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import productModel from '../models/productModel.js';
import fs from 'fs';
import slugify from 'slugify';

export const createProductController = async (req, res) => {
try {
const { name, slug, description, price, category, quantity, shipping } =
req.fields;
const { photo } = req.files;
//validation
switch (true) {
case !name:
return res.status(500).send({ error: 'Name is Required' });
case !description:
return res.status(500).send({ error: 'Description is Required' });
case !price:
return res.status(500).send({ error: 'Price is Required' });
case !category:
return res.status(500).send({ error: 'Category is Required' });
case !quantity:
return res.status(500).send({ error: 'Quantity is Required' });
case !photo && photo.size > 1000000:
return res
.status(500)
.send({ error: 'Photo is Required and should be less than 1mb' });
}
const products = new productModel({ ...req.fields, slug: slugify(name) });
if (photo) {
products.photo.data = fs.readFileSync(photo.path);
products.photo.contentType = photo.type;
}
await products.save();
res.status(201).send({
success: true,
message: 'Product Created Successfully',
products,
});
} catch (error) {
console.log(error);
res.status(500).send({
success: false,
error,
message: 'Error in Creating the Product',
});
}
};

//update product
export const updateProductController = async (req, res) => {
try {
const { name, slug, description, price, category, quantity, shipping } =
req.fields;
const { photo } = req.files;
//validation
switch (true) {
case !name:
return res.status(500).send({ error: 'Name is Required' });
case !description:
return res.status(500).send({ error: 'Description is Required' });
case !price:
return res.status(500).send({ error: 'Price is Required' });
case !category:
return res.status(500).send({ error: 'Category is Required' });
case !quantity:
return res.status(500).send({ error: 'Quantity is Required' });
case !photo && photo.size > 1000000:
return res
.status(500)
.send({ error: 'Photo is Required and should be less than 1mb' });
}
const products = await productModel.findByIdAndUpdate(
req.params.pid,
{ ...req.fields, slug: slugify(name) },
{ new: true }
);
if (photo) {
products.photo.data = fs.readFileSync(photo.path);
products.photo.contentType = photo.type;
}
await products.save();
res.status(201).send({
success: true,
message: 'Product Updated Successfully',
products,
});
} catch (error) {
console.log(error);
res.status(500).send({
success: false,
error,
message: 'Error in Updte product',
});
}
};

//get all products
export const getProductController = async (req, res) => {
try {
const products = await productModel
.find({})
.populate('category')
.select('-photo')
.limit(12)
.sort({ createdAt: -1 });
res.status(200).send({
success: true,
total: products.length,
message: 'All Products',
products,
});
} catch (error) {
console.log(error),
res.status(500).send({
success: false,
error,
message: 'Error in getting products',
});
}
};

//get single product
export const getSingleProductController = async (req, res) => {
try {
const product = await productModel
.findOne({ slug: req.params.slug })
.select('-photo')
.populate('category');
res.status(200).send({
success: true,
message: 'Single Product Fetched',
product,
});
} catch (error) {
console.log(error);
res.status(500).send({
success: false,
error,
message: 'Error while getting a single product',
});
}
};

//get photo
export const productPhotoController = async (req, res) => {
try {
const product = await productModel.findById(req.params.pid).select('photo');
if (product.photo.data) {
res.set('Content-type', product.photo.contentType);
return res.status(200).send(product.photo.data);
}
} catch (error) {
console.log(error);
res.status(500).send({
success: false,
error,
message: 'Error while fetching the photo',
});
}
};

//delete product
export const deleteProductController = async (req, res) => {
try {
const { pid } = req.params;
await productModel.findByIdAndDelete(pid).select('-photo');
res.status(200).send({
success: true,
message: 'Product Deleted Successfully!',
});
} catch (error) {
console.log(error);
res.status(500).send({
success: false,
error,
message: 'Error while Deleting the Product',
});
}
};
41 changes: 41 additions & 0 deletions models/productModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import mongoose from 'mongoose';

const productSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
unique: true,
},
slug: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
category: {
type: mongoose.ObjectId,
ref: 'Category',
},
quantity: {
type: Number,
required: true,
},
photo: {
data: Buffer,
contentType: String,
},
shipping: {
type: Boolean,
},
},
{ timestamps: true }
);

export default mongoose.model('Products', productSchema);
20 changes: 20 additions & 0 deletions node_modules/.package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions node_modules/express-formidable/.eslintrc

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions node_modules/express-formidable/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit a973bf6

Please sign in to comment.