Skip to content

Commit

Permalink
ADDED NEW API
Browse files Browse the repository at this point in the history
  • Loading branch information
sujal-98 committed May 18, 2024
1 parent e2a1a70 commit 46a4356
Show file tree
Hide file tree
Showing 14 changed files with 628 additions and 0 deletions.
8 changes: 8 additions & 0 deletions New_APIs/Ecom/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Ignore node_modules directory
node_modules/

# Ignore .env files
.env


package-lock.json
28 changes: 28 additions & 0 deletions New_APIs/Ecom/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# **Ecom API**

### Overview
This project is an Express.js based API for managing users, authentication, products, carts, and orders. It provides endpoints for CRUD operations on these resources and includes authentication and authorization middleware.

### Prerequisites
Before you begin, ensure you have met the following requirements:

Node.js installed
MongoDB installed and running
npm installed

### Installation

**Clone the repository:**
git clone https://github.com/your-username/repository-name.git
cd repository-name

**Install dependencies:**
npm install


### Create a .env file in the root directory and add your environment variables:

PORT=Your_Desired_Port
MONGO_URL=your_mongodb_connection_string
JWT_SECRET=your_jwt_secret
SECRET_PHRASE=your_secret_phrase
35 changes: 35 additions & 0 deletions New_APIs/Ecom/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const express=require('express');
const app=express();
const dotenv=require('dotenv')
dotenv.config();
const mongoose=require('mongoose')
const userRoute=require('./routes/user')
const authRoute=require('./routes/auth')
const prodRoute=require('./routes/prod')
const carRoute=require('./routes/car')
const orderRoute=require('./routes/ord')



mongoose.connect(process.env.url
).then(()=>{
console.log("Db connection successfull"
)
}).catch((err)=>{
console.log(err);
})


//middlewares

app.use(express.json())
app.use("/api/auth",authRoute)
app.use("/api/user",userRoute)
app.use("/api/prod",prodRoute)
app.use("/api/car",carRoute)
app.use("/api/ord",orderRoute)


app.listen(process.env.Port,()=>{
console.log("server running");
})
14 changes: 14 additions & 0 deletions New_APIs/Ecom/models/cart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose=require('mongoose')

const CartSchema=new mongoose.Schema({
userId:{type:String,required:true},
products:[{
product:{type:String,required:true},
quantity:{
type:Number,
default:1
}
}]
},{timestamps:true});

module.exports=mongoose.model('Cart',CartSchema)
17 changes: 17 additions & 0 deletions New_APIs/Ecom/models/order.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const mongoose=require('mongoose')

const OrderSchema=new mongoose.Schema({
userId:{type:String,required:true},
products:[{
product:{type:String,required:true},
quantity:{
type:Number,
default:1
}
}],
amount:{type:Number,required:true},
address:{type:Object,required:true},
status:{type:String, default:"pending"}
},{timeStamps:true});

module.exports=mongoose.model('order',OrderSchema)
14 changes: 14 additions & 0 deletions New_APIs/Ecom/models/product.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose=require('mongoose')

const ProductSchema=new mongoose.Schema({
title:{type:String,required:true,unique:true},
description:{type:String,required:true,unique:true},
img:{type:String,required:true,unique:true},
categories:{type:Array},
size:{type:String},
color:{type:String},
price:{type:String,required:true,unique:true},

},{timestamps:true});

module.exports=mongoose.model('Product',ProductSchema)
13 changes: 13 additions & 0 deletions New_APIs/Ecom/models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const mongoose=require('mongoose')

const UserSchema=new mongoose.Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
password:{type:String,required:true,unique:true},
isAdmin:{
type:Boolean,
default: false
},
},{timestamps:true});

module.exports=mongoose.model('User',UserSchema)
21 changes: 21 additions & 0 deletions New_APIs/Ecom/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "ecom",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"crypto-js": "^4.2.0",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.3.1",
"stripe": "^15.0.0"
}
}
54 changes: 54 additions & 0 deletions New_APIs/Ecom/routes/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const router=require('express').Router();
const User=require('../models/user')
const crypto=require("crypto-js")
const jwt=require('jsonwebtoken')

router.post("/register",async(req,res)=>{
const newuser=new User({
username:req.body.username,
email:req.body.email,
password:crypto.AES.encrypt(req.body.password,process.env.secretphrase).toString()
});
try{
const saved=await newuser.save();
res.status(201).json(saved)}
catch(err){
res.status(500).json(err);
}
})

//login route
router.post("/login", async (req, res, next) => {
try {
const user = await User.findOne({ username: req.body.username });

if (!user) {
return res.status(401).json("Wrong credentials1");
}

const hash = crypto.AES.decrypt(user.password, process.env.secretphrase);
let originalpass = hash.toString(crypto.enc.Utf8);

if (originalpass !== req.body.password) {
return res.status(401).json("Wrong credentials2");
}

const access=jwt.sign({
id:user._id,
isAdmin:user.isAdmin,
},
process.env.jwtsecret,
{expiresIn:'3d'}
)
console.log(user._doc)
const { password, ...others } = user._doc;

res.status(200).json({...others,access});
} catch (err) {
res.status(500).json(err);
}
});



module.exports=router;
79 changes: 79 additions & 0 deletions New_APIs/Ecom/routes/car.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
const router=require('express').Router();
const cart = require('../models/cart');
const { verifyToken, verifynauth, verifynadmin } = require('./verifytoken');

//create

router.post("/add",verifyToken,async (req,res)=>{
const newc=new cart(req.body)
try{
const saved=await newc.save();
res.status(200).json(saved)
}catch(err){
res.status(500).json(err);
}
})

//updates

router.put("/upd/:id",verifyToken,async (req,res)=>{
try {
const updated = await cart.findByIdAndUpdate(req.params.id, { $set: req.body }, { new: true });
if (!updated) {
return res.status(404).json({ error: "product not found" });
}
res.status(200).json(updated);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
}
)


//delete
router.delete("/del/:id",verifyToken,async (req,res)=>{
try{
await cart.findByIdAndDelete(req.params.id)
res.status(200).json("product has been deleted")
}
catch(err){
res.status(500).json(err)
}}
)

//get products

router.get("/find/:id",async(req,res)=>{
try{
console.log(req.params.id)
const a=await cart.findOne({userId:req.params.id})
console.log(a)
if(!a){
res.status(405).json("Not found")
}
console.log(a._doc)
const { password, ...others } = a._doc;
res.status(200).json({others});
}
catch(err){
res.status(500).json("sorry again")
}
})

//get all prod

router.get("/",verifynadmin,async(req,res)=>{
try{

const cart=await cart.find()
res.statusMessage(200).json(cart)

}catch(err){
res.status(500).json(err)
}

})


module.exports=router;
Loading

0 comments on commit 46a4356

Please sign in to comment.