'getapibugs-rectified'

parent 1c59899a
const express=require('express')
const {connectToDb, getDb} = require("./db")
const {ObjectId}=require("mongodb")
const cors= require("cors")
const app=express();
const express = require('express')
const { connectToDb, getDb } = require("./db")
const { ObjectId } = require("mongodb")
const cors = require("cors")
const app = express();
app.use(express.json())
app.use(cors())
connectToDb((err)=>{
if(!err){
app.listen(4000, ()=>{
connectToDb((err) => {
if (!err) {
app.listen(4000, () => {
console.log('app listening on port 4000')
})
db=getDb()
db = getDb()
}
})
app.get('/products', (req, res) => {
db.collection('products').find().toArray()
.then(result => {res.send(result)})
.catch(error => res.status(500).send(error))
.then(result => { res.send(result) })
.catch(error => res.status(500).send(error))
})
// app.get('/products', (req, res) => {
......@@ -34,73 +34,83 @@ app.get('/products', (req, res) => {
// })
app.get('/products/:id', (req, res) => {
const Id = Number(req.params.id)
if(!isNaN(Id)){
db.collection('products').find({id: Id}).toArray()
.then(result => { res.send(result) })
.catch(error => res.status(500).send(error))
const id = req.params.id;
if (!isNaN(id)) {
const numericId = Number(id);
db.collection('products').findOne({ id: numericId })
.then(result => {
if (result != null) {
res.status(200).json(result);
} else {
res.status(404).json({ error: 'Product not found' });
}
})
.catch(error => res.status(400).json({ error: 'Invalid ID' }));
} else if (/^[a-zA-Z]+$/.test(id)) {
res.status(404).json({ error: 'Invalid ID' });
} else {
res.status(500).json({ error: 'Invalid ID' })
res.status(400).json({ error: 'Invalid ID' });
}
})
});
// Middleware function to check if userId already exists
const checkUserIdExists = (req, res, next) => {
const userId = req.body.userId.trim();
db.collection('users').findOne({ userId: userId })
.then(result => {
if (result) {
res.status(400).json({ error: "userId already exists" });
} else {
next(); // Proceed to register user if userId is not taken
}
})
.catch(error => res.status(500).json({ error: "Internal server error" }));
.then(result => {
if (result) {
res.status(400).json({ error: "userId already exists" });
} else {
next(); // Proceed to register user if userId is not taken
}
})
.catch(error => res.status(500).json({ error: "Internal server error" }));
};
// Register User endpoint with middleware
app.post('/registeruser', checkUserIdExists, (req, res) => {
const user = req.body;
const userid=req.body.userId;
const userid = req.body.userId;
db.collection('users').insertOne(user)
.then(result => {
res.status(201).json(result);
db.collection('cartitems').insertOne({userId:userid,cartItems:[]})
})
.catch(err => res.status(500).json({ error: "Could not create a new document" }));
.then(result => {
res.status(201).json(result);
db.collection('cartitems').insertOne({ userId: userid, cartItems: [] })
})
.catch(err => res.status(500).json({ error: "Could not create a new document" }));
});
// Get Users endpoint
app.get('/users', (req, res) => {
// db.collection('users').find({}, { projection: { _id: false, userId: true, password: true } }).toArray()
db.collection('users').find({}, { projection: { _id: false} }).toArray()
.then(result => {
res.send(result);
})
.catch(error => res.status(500).send(error));
db.collection('users').find({}, { projection: { _id: false } }).toArray()
.then(result => {
res.send(result);
})
.catch(error => res.status(500).send(error));
});
app.delete('/deregister/:userid', (req, res) => {
const userid = req.params.userid
if(isNaN(userid)){
db.collection('users').deleteOne({userId:userid})
.then(result => {
res.send(result)
db.collection('cartitems').deleteOne({userId:userid})
})
.catch(error => res.status(500).send(error))
if (isNaN(userid)) {
db.collection('users').deleteOne({ userId: userid })
.then(result => {
res.send(result)
db.collection('cartitems').deleteOne({ userId: userid })
})
.catch(error => res.status(500).send(error))
} else {
res.status(500).json({ error: 'Invalid ID' })
}
})
app.patch('/updateuser/:id', (req, res) => {
const Id = req.params.id
const data = req.body
if(ObjectId.isValid(Id)){
db.collection('users').updateOne({_id:new ObjectId(Id)},{$set:data})
.then(result => { res.send(result) })
.catch(error => res.status(500).send(error))
if (ObjectId.isValid(Id)) {
db.collection('users').updateOne({ _id: new ObjectId(Id) }, { $set: data })
.then(result => { res.send(result) })
.catch(error => res.status(500).send(error))
} else {
res.status(500).json({ error: 'Invalid ID' })
}
......@@ -108,12 +118,19 @@ app.patch('/updateuser/:id', (req, res) => {
app.get('/cartItems/:userid', (req, res) => {
const userid = req.params.userid
if(isNaN(userid)){
db.collection('cartitems').findOne({userId: userid})
.then(result => { res.send(result) })
const usernameRegex = /^[a-zA-Z0-9_]{1,10}$/;
if (usernameRegex.test(userid)) {
db.collection('cartitems').findOne({ userId: userid })
.then(result => {
if (result != null) {
res.status(200).send(result);
} else {
res.status(404).json({ error: 'UserCart not found' });
}
})
.catch(error => res.status(500).send(error))
} else {
res.status(500).json({ error: 'Invalid UserId' })
res.status(400).json({ error: 'Invalid UserId' })
}
})
......@@ -122,7 +139,7 @@ app.patch('/updateCartItems/:userid', async (req, res) => {
const newCartItem = req.body;
// Check if userid is a number
if (!isNaN(userid)) {
if (!isNaN(userid)) {
return res.status(400).json({ error: 'Invalid UserId' });
}
......@@ -147,7 +164,7 @@ app.patch('/updateCartItems/:userid', async (req, res) => {
// }
// // Update the cart with the modified cartItems
// await db.collection('cartitems').updateOne({ userId: userid }, { $set: { cartItems: cart.cartItems } });
await db.collection('cartitems').updateOne({ userId: userid }, { $set: { cartItems: newCartItem} });
await db.collection('cartitems').updateOne({ userId: userid }, { $set: { cartItems: newCartItem } });
return res.status(200).json({ message: 'Cart updated successfully' });
} catch (error) {
return res.status(500).json({ error: error.message });
......
import React, { memo } from 'react';
const Error = memo(() => {
return (
<div className='d-flex justify-content-center align-items-center' style={{height:'200px'}}>
<div className='d-flex flex-column align-items-center my-5'>
<code className='fs-1'>Error 404 <span className='bi bi-bug-fill'></span></code>
<br/>
<code className='fs-1'>Page Not Found</code>
</div>
</div>
);
});
export default Error;
\ No newline at end of file
......@@ -45,7 +45,7 @@ const Cart = memo(() => {
return (
<div>
<div>
<button type="button" className="btn btn-primary mx-2 position-relative" data-bs-toggle="modal" data-bs-target="#cartModal">
<button type="button" className="btn btn-primary mx-3 position-relative" data-bs-toggle="modal" data-bs-target="#cartModal">
<span className='bi bi-cart'></span> Cart
<span className="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
{cartItems!=null?<span>{cartItems.length}</span>:0}
......@@ -59,9 +59,9 @@ const Cart = memo(() => {
<h1 className="modal-title fs-5" id="cartModalLabel">{capitalizedUserId}'s Cart</h1>
{/* <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> */}
</div>
<div className="modal-body">
<table className='table table-hover m-0'>
<thead>
<div className="modal-body m-0 pt-0" style={{maxHeight:'350px',minHeight:'250px',scrollbarWidth:'thin',overflowY:'scroll'}}>
<table className='table table-hover' >
<thead className='position-sticky top-0 bg-white'>
<tr>
<th>Preview</th>
<th>Price</th>
......
......@@ -24,7 +24,7 @@ const NavButtons = memo((props:NavButtonsProps) => {
<Profile/>
<Cart/>
<Link to="/">
<button className='btn btn-danger' onClick={props.handleLogout}>Logout</button>
<button className='btn btn-danger me-2' onClick={props.handleLogout}>Logout</button>
</Link>
</>
) }
......
......@@ -49,6 +49,9 @@ const Register = () => {
}
})
}
if (values.userId !== "" && values.userId.length > 10) {
errors.userIdErr = "UserId should be only upto 10 characters"
}
if (values.fname != "" && values.fname.length <= 4) {
errors.fnameErr = "Name should be more than 4 characters"
} else {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment