'getapibugs-rectified'

parent 1c59899a
const express=require('express') const express = require('express')
const {connectToDb, getDb} = require("./db") const { connectToDb, getDb } = require("./db")
const {ObjectId}=require("mongodb") const { ObjectId } = require("mongodb")
const cors= require("cors") const cors = require("cors")
const app=express(); const app = express();
app.use(express.json()) app.use(express.json())
app.use(cors()) app.use(cors())
connectToDb((err)=>{ connectToDb((err) => {
if(!err){ if (!err) {
app.listen(4000, ()=>{ app.listen(4000, () => {
console.log('app listening on port 4000') console.log('app listening on port 4000')
}) })
db=getDb() db = getDb()
} }
}) })
app.get('/products', (req, res) => { app.get('/products', (req, res) => {
db.collection('products').find().toArray() db.collection('products').find().toArray()
.then(result => {res.send(result)}) .then(result => { res.send(result) })
.catch(error => res.status(500).send(error)) .catch(error => res.status(500).send(error))
}) })
...@@ -34,15 +34,25 @@ app.get('/products', (req, res) => { ...@@ -34,15 +34,25 @@ app.get('/products', (req, res) => {
// }) // })
app.get('/products/:id', (req, res) => { app.get('/products/:id', (req, res) => {
const Id = Number(req.params.id) const id = req.params.id;
if(!isNaN(Id)){
db.collection('products').find({id: Id}).toArray() if (!isNaN(id)) {
.then(result => { res.send(result) }) const numericId = Number(id);
.catch(error => res.status(500).send(error)) db.collection('products').findOne({ id: numericId })
.then(result => {
if (result != null) {
res.status(200).json(result);
} else { } else {
res.status(500).json({ error: 'Invalid ID' }) 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(400).json({ error: 'Invalid ID' });
}
});
// Middleware function to check if userId already exists // Middleware function to check if userId already exists
const checkUserIdExists = (req, res, next) => { const checkUserIdExists = (req, res, next) => {
...@@ -61,11 +71,11 @@ const checkUserIdExists = (req, res, next) => { ...@@ -61,11 +71,11 @@ const checkUserIdExists = (req, res, next) => {
// Register User endpoint with middleware // Register User endpoint with middleware
app.post('/registeruser', checkUserIdExists, (req, res) => { app.post('/registeruser', checkUserIdExists, (req, res) => {
const user = req.body; const user = req.body;
const userid=req.body.userId; const userid = req.body.userId;
db.collection('users').insertOne(user) db.collection('users').insertOne(user)
.then(result => { .then(result => {
res.status(201).json(result); res.status(201).json(result);
db.collection('cartitems').insertOne({userId:userid,cartItems:[]}) db.collection('cartitems').insertOne({ userId: userid, cartItems: [] })
}) })
.catch(err => res.status(500).json({ error: "Could not create a new document" })); .catch(err => res.status(500).json({ error: "Could not create a new document" }));
}); });
...@@ -73,7 +83,7 @@ app.post('/registeruser', checkUserIdExists, (req, res) => { ...@@ -73,7 +83,7 @@ app.post('/registeruser', checkUserIdExists, (req, res) => {
// Get Users endpoint // Get Users endpoint
app.get('/users', (req, res) => { app.get('/users', (req, res) => {
// db.collection('users').find({}, { projection: { _id: false, userId: true, password: true } }).toArray() // db.collection('users').find({}, { projection: { _id: false, userId: true, password: true } }).toArray()
db.collection('users').find({}, { projection: { _id: false} }).toArray() db.collection('users').find({}, { projection: { _id: false } }).toArray()
.then(result => { .then(result => {
res.send(result); res.send(result);
}) })
...@@ -82,11 +92,11 @@ app.get('/users', (req, res) => { ...@@ -82,11 +92,11 @@ app.get('/users', (req, res) => {
app.delete('/deregister/:userid', (req, res) => { app.delete('/deregister/:userid', (req, res) => {
const userid = req.params.userid const userid = req.params.userid
if(isNaN(userid)){ if (isNaN(userid)) {
db.collection('users').deleteOne({userId:userid}) db.collection('users').deleteOne({ userId: userid })
.then(result => { .then(result => {
res.send(result) res.send(result)
db.collection('cartitems').deleteOne({userId:userid}) db.collection('cartitems').deleteOne({ userId: userid })
}) })
.catch(error => res.status(500).send(error)) .catch(error => res.status(500).send(error))
} else { } else {
...@@ -97,8 +107,8 @@ app.delete('/deregister/:userid', (req, res) => { ...@@ -97,8 +107,8 @@ app.delete('/deregister/:userid', (req, res) => {
app.patch('/updateuser/:id', (req, res) => { app.patch('/updateuser/:id', (req, res) => {
const Id = req.params.id const Id = req.params.id
const data = req.body const data = req.body
if(ObjectId.isValid(Id)){ if (ObjectId.isValid(Id)) {
db.collection('users').updateOne({_id:new ObjectId(Id)},{$set:data}) db.collection('users').updateOne({ _id: new ObjectId(Id) }, { $set: data })
.then(result => { res.send(result) }) .then(result => { res.send(result) })
.catch(error => res.status(500).send(error)) .catch(error => res.status(500).send(error))
} else { } else {
...@@ -108,12 +118,19 @@ app.patch('/updateuser/:id', (req, res) => { ...@@ -108,12 +118,19 @@ app.patch('/updateuser/:id', (req, res) => {
app.get('/cartItems/:userid', (req, res) => { app.get('/cartItems/:userid', (req, res) => {
const userid = req.params.userid const userid = req.params.userid
if(isNaN(userid)){ const usernameRegex = /^[a-zA-Z0-9_]{1,10}$/;
db.collection('cartitems').findOne({userId: userid}) if (usernameRegex.test(userid)) {
.then(result => { res.send(result) }) 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)) .catch(error => res.status(500).send(error))
} else { } else {
res.status(500).json({ error: 'Invalid UserId' }) res.status(400).json({ error: 'Invalid UserId' })
} }
}) })
...@@ -147,7 +164,7 @@ app.patch('/updateCartItems/:userid', async (req, res) => { ...@@ -147,7 +164,7 @@ app.patch('/updateCartItems/:userid', async (req, res) => {
// } // }
// // Update the cart with the modified cartItems // // 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: 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' }); return res.status(200).json({ message: 'Cart updated successfully' });
} catch (error) { } catch (error) {
return res.status(500).json({ error: error.message }); 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(() => { ...@@ -45,7 +45,7 @@ const Cart = memo(() => {
return ( return (
<div> <div>
<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='bi bi-cart'></span> Cart
<span className="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"> <span className="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
{cartItems!=null?<span>{cartItems.length}</span>:0} {cartItems!=null?<span>{cartItems.length}</span>:0}
...@@ -59,9 +59,9 @@ const Cart = memo(() => { ...@@ -59,9 +59,9 @@ const Cart = memo(() => {
<h1 className="modal-title fs-5" id="cartModalLabel">{capitalizedUserId}'s Cart</h1> <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> */} {/* <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> */}
</div> </div>
<div className="modal-body"> <div className="modal-body m-0 pt-0" style={{maxHeight:'350px',minHeight:'250px',scrollbarWidth:'thin',overflowY:'scroll'}}>
<table className='table table-hover m-0'> <table className='table table-hover' >
<thead> <thead className='position-sticky top-0 bg-white'>
<tr> <tr>
<th>Preview</th> <th>Preview</th>
<th>Price</th> <th>Price</th>
......
...@@ -24,7 +24,7 @@ const NavButtons = memo((props:NavButtonsProps) => { ...@@ -24,7 +24,7 @@ const NavButtons = memo((props:NavButtonsProps) => {
<Profile/> <Profile/>
<Cart/> <Cart/>
<Link to="/"> <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> </Link>
</> </>
) } ) }
......
...@@ -49,6 +49,9 @@ const Register = () => { ...@@ -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) { if (values.fname != "" && values.fname.length <= 4) {
errors.fnameErr = "Name should be more than 4 characters" errors.fnameErr = "Name should be more than 4 characters"
} else { } 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