Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode problem : Fruit Basket #371

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
242 changes: 110 additions & 132 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,132 +1,110 @@
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const cors = require('cors');

// Import required modules

// Create an Express app
const app = express();

// Enable CORS
app.use(express.json());
app.use(cors());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/cafe', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});

// Define a user schema
const userSchema = new mongoose.Schema({
username: { type: String, required: true },
password: { type: String, required: true }
});

// Define a user model
const User = mongoose.model('User', userSchema);
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, required: true },
quantity: { type: Number, required: true }
});
const Product = mongoose.model('Product', productSchema);
// Register a new user
app.post('/register', async (req, res) => {
try {
const { username, password } = req.body;

// Check if the username already exists
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(400).json({ message: 'Username already exists' });
}

// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);

// Create a new user
const newUser = new User({ username, password: hashedPassword });
await newUser.save();

res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
console.error('Error registering user:', error);
res.status(500).json({ message: 'Internal server error' });
}
});

// User login
app.post('/login', async (req, res) => {
try {
const { username, password } = req.body;

// Find the user by username
const user = await User.findOne({ username });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}

// Compare the password
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ message: 'Invalid password' });
}

res.status(200).json({ message: 'Login successful' });
} catch (error) {
console.error('Error logging in:', error);
res.status(500).json({ message: 'Internal server error' });
}
});

app.get('/products',async (req,res)=>{
try{
const products = await Product.find();
res.status(200).json(products);
}catch(error){
console.error('Error getting products:',error);
res.status(500).json({message:'Internal server error'});
}
})

app.post('/products',async (req,res)=>{
try{
const {name,price,quantity} = req.body;
const newProduct = new Product({name,price,quantity});
await newProduct.save();
res.status(201).json({message:'Product added successfully'});
}catch(error){
console.error('Error adding product:',error);
res.status(500).json({message:'Internal server error'});
}
})

app.put('/products/:id',async (req,res)=>{
try{
const {name,price,quantity} = req.body;
await Product.findByIdAndUpdate(req.params.id,{name,price,quantity});
res.status(200).json({message:'Product updated successfully'});
}catch(error){
console.error('Error updating product:',error);
res.status(500).json({message:'Internal server error'});
}
})

app.delete('/products/:id',async (req,res)=>{
try{
await Product.findByIdAndDelete(req.params.id);
res.status(200).json({message:'Product deleted successfully'});
}catch(error){
console.error('Error deleting product:',error);
res.status(500).json({message:'Internal server error'});
}
})
// Start the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});
import React, { useState } from "react";
import "./App.css";

function App() {
const [expenses, setExpenses] = useState([]);
const [description, setDescription] = useState("");
const [amount, setAmount] = useState("");
const [category, setCategory] = useState("");
const [editId, setEditId] = useState(null);

// Add new expense
const addExpense = () => {
if (editId !== null) {
const updatedExpenses = expenses.map((expense) =>
expense.id === editId
? { ...expense, description, amount, category }
: expense
);
setExpenses(updatedExpenses);
setEditId(null);
} else {
const newExpense = {
id: Date.now(),
description,
amount: parseFloat(amount),
category,
};
setExpenses([...expenses, newExpense]);
}
resetFields();
};

// Delete expense
const deleteExpense = (id) => {
setExpenses(expenses.filter((expense) => expense.id !== id));
};

// Edit expense
const editExpense = (id) => {
const expense = expenses.find((expense) => expense.id === id);
setDescription(expense.description);
setAmount(expense.amount);
setCategory(expense.category);
setEditId(id);
};

// Reset input fields
const resetFields = () => {
setDescription("");
setAmount("");
setCategory("");
};

// Calculate total expenses
const totalExpenses = expenses.reduce((acc, expense) => acc + expense.amount, 0);

return (
<div className="App">
<h1>Expense Tracker</h1>

<div className="form">
<input
type="text"
placeholder="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<input
type="number"
placeholder="Amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
/>
<input
type="text"
placeholder="Category"
value={category}
onChange={(e) => setCategory(e.target.value)}
/>
<button onClick={addExpense}>
{editId !== null ? "Update Expense" : "Add Expense"}
</button>
</div>

<div className="expense-list">
<h2>Your Expenses</h2>
{expenses.length === 0 ? (
<p>No expenses added yet</p>
) : (
<ul>
{expenses.map((expense) => (
<li key={expense.id}>
<strong>{expense.description}</strong> - ${expense.amount} -{" "}
{expense.category}
<button onClick={() => editExpense(expense.id)}>Edit</button>
<button onClick={() => deleteExpense(expense.id)}>Delete</button>
</li>
))}
</ul>
)}
</div>

<div className="summary">
<h2>Total Expenses: ${totalExpenses.toFixed(2)}</h2>
</div>
</div>
);
}

export default App;