17
loading...
This website collects cookies to deliver better user experience
npm init -y
npm install cors dotenv express mongoose nodemon body-parser
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.13",
"nodemon": "^2.0.15"
}
}
Import express module.
Import mongoose module
Import and configure dotenv module
Import CORS module
Use express() to start our app.
//app.js
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
const app = express();
// app.js
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
// app.js
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
const app = express();
// app config
app.use(cors());
app.use(express.json());
// port and DB config
const DATABASE_CONNECTION = process.env.DATABASE_URL;
const PORT = process.env.PORT || 5000;
// mongoose connection
mongoose
.connect(DATABASE_CONNECTION, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() =>
app.listen(PORT, () =>
console.log(`Server is running at : http://localhost:${PORT}`)
)
)
.catch((error) => console.error(error));
PORT=6000
DATABASE_URL=mongodb+srv://pramit:<password>@cluster0.uauqv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
//app.js
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
const app = express();
// app config
app.use(cors());
app.use(express.json());
// port and DB config
const DATABASE_CONNECTION = process.env.DATABASE_URL;
const PORT = process.env.PORT || 5000;
// mongoose connection
mongoose
.connect(DATABASE_CONNECTION, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() =>
app.listen(PORT, () =>
console.log(`Server is running at : http://localhost:${PORT}`)
)
)
.catch((error) => console.error(error));
// routers
const calorie = require("./routes/calorie.routes.js");
const users = require("./routes/users.routes.js");
app.use("/calorie", calorie);
app.use("/users", users);
//models/calorie.model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const calorieSchema = new Schema({
username: {
type: String,
required: true
},
description: {
type: String,
required: true
},
calories: {
type: Number,
required: true
},
date: {
type: Date,
required: true
},
}, {
timestamps: true,
});
const Calorie = mongoose.model("CalorieJournal", calorieSchema);
module.exports = Calorie;
//models/users.model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 2,
},
}, {
timestamps: true,
});
const User = mongoose.model("User", userSchema);
module.exports = User;
//routes/calorie.routes.js
const router = require("express").Router();
let Calorie = require("../models/calorie.model.js");
router.route("/").get((req, res) => {
Calorie.find()
.then((meals) => res.json(meals))
.catch((err) => res.status(400).json("Error: " + err));
});
router.route("/add").post((req, res) => {
const username = req.body.username;
const description = req.body.description;
const calories = Number(req.body.calories);
const date = Date.parse(req.body.date);
const addCalorie = new Calorie({
username,
description,
calories,
date,
});
addCalorie
.save()
.then(() => res.json("Calories Added Successfully"))
.catch((err) => res.status(400).json("Error: " + err));
});
//models/calorie.model.js
const router = require("express").Router();
let Calorie = require("../models/calorie.model.js");
router.route("/").get((req, res) => {
Calorie.find()
.then((meals) => res.json(meals))
.catch((err) => res.status(400).json("Error: " + err));
});
router.route("/add").post((req, res) => {
const username = req.body.username;
const description = req.body.description;
const calories = Number(req.body.calories);
const date = Date.parse(req.body.date);
const addCalorie = new Calorie({
username,
description,
calories,
date,
});
addCalorie
.save()
.then(() => res.json("Calories Added Successfully"))
.catch((err) => res.status(400).json("Error: " + err));
});
router.route("/:id").get((req, res) => {
Calorie.findById(req.params.id)
.then((calories) => res.json(calories))
.catch((err) => res.status(400).json("Error: " + err));
});
router.route("/:id").delete((req, res) => {
Calorie.findByIdAndDelete(req.params.id)
.then(() => res.json("Calories is deleted Successfully"))
.catch((err) => res.status(400).json("Error: " + err));
});
router.route("/update/:id").post((req, res) => {
Calorie.findById(req.params.id)
.then((calories) => {
calories.username = req.body.username;
calories.description = req.body.description;
calories.calories = Number(req.body.calories);
calories.date = Date.parse(req.body.date);
calories
.save()
.then(() => res.json("Calorie Updated Successfully"))
.catch((err) => res.status(400).json("Err: " + err));
})
.catch((err) => res.status(400).json("Err: " + err));
});
module.exports = router;
//routes/user.routes.js
const router = require("express").Router();
let User = require("../models/users.model.js");
//routes/user.routes.js
const router = require("express").Router();
let User = require("../models/users.model.js");
// get user
router.route("/").get((req, res) => {
User.find()
.then((users) => res.json(users))
.catch((err) => res.status(400).json("Error: " + err));
});
// add user
router.route("/add").post((req, res) => {
const username = req.body.username;
const newUser = new User({
username
});
newUser
.save()
.then(() => res.json("User added Successfully"))
.catch((err) => res.status(400).json("Error: " + err));
});
module.exports = router;
npm install bootstrap react-chartjs-2 chart.js axios react-datepicker react-router-dom
// app.js
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import Navbar from "./components/Navbar";
import DisplayFoodList from "./components/DisplayFoodList";
import EditFood from "./components/EditFood";
import AddFood from "./components/AddFood";
import AddUser from "./components/AddUser";
function App() {
return (
<>
<Router>
<Navbar />
<br />
<Routes>
<Route path="/" exact element={<DisplayFoodList />} />
<Route path="/edit/:id" element={<EditFood />} />
<Route path="/create" element={<AddFood />} />
<Route path="/user" element={<AddUser />} />
</Routes>
</Router>
</>
);
}
export default App;
//components/Navbar/Navbar.js
import React from "react";
import { Link } from "react-router-dom";
const Navbar = () => {
return (
<nav
className="navbar navbar-expand-lg navbar-light static-top mb-0 shadow"
style={{ backgroundColor: "#8661d1" }}
>
<div className="container">
<Link to="/">
<img
alt="Calorie Journal Logo"
src="https://user-images.githubusercontent.com/37651620/142762093-45207811-0c6e-4b62-9cb2-8d0009efb4ea.png"
width="70"
height="70"
className="d-inline-block align-top"
/>
</Link>
<Link
className="navbar-brand"
to="/"
className="navbar-brand"
style={{
color: "white",
fontSize: "1.5rem",
marginRight: "15rem",
marginLeft: "30rem",
}}
>
<img
src="https://user-images.githubusercontent.com/37651620/142764762-fef8f764-4cd5-44c6-8b9a-cffcfab2ccf8.png"
alt="calorie journal"
style={{ height: "100px" }}
/>
</Link>
<div className="collapse navbar-collapse">
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<Link
className="nav-link"
to="/"
className="nav-link"
style={{
fontSize: "0.2rem",
color: "white",
}}
>
<button type="button" className="btn btn-info">
Calorie Info
</button>
</Link>
</li>
<li className="nav-item active">
<Link
className="nav-link"
to="/create"
className="nav-link"
style={{
fontSize: "0.2rem",
color: "white",
}}
>
<button type="button" className="btn btn-info">
➕ Add food
</button>
</Link>
</li>
<li className="nav-item">
<Link
className="nav-link"
to="/user"
className="nav-link"
style={{
fontSize: "0.2rem",
color: "white",
}}
>
<button type="button" className="btn btn-warning">
➕ Add User
</button>
</Link>
</li>
</ul>
</div>
</div>
</nav>
);
};
export default Navbar;
import React,{useState,useEffect,useRef} from "react";
import axios from "axios";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
const [state, setState] = useState(initialState);
const refContainer = useRef(initialValue);
const userInputRef = useRef("userInput");
useEffect(() => {
axios
.get("http://localhost:5000/users/")
.then((response) => {
if (response.data.length > 0) {
setUsers(response.data.map((user) => user.username));
setUsername(response.data[0].username);
}
})
.catch((error) => {
console.log(error);
});
}, []);
function handleUsername(e) {
setUsername(e.target.value);
}
function handleDescription(e) {
setDescription(e.target.value);
}
function handleCalories(e) {
setCalories(e.target.value);
}
function handleDate(date) {
setDate(date);
}
function handleSubmit(e) {
e.preventDefault();
const meal = {
username,
description,
calories,
date,
};
console.log(meal);
axios
.post("http://localhost:5000/calorie/add", meal)
.then((res) => console.log(res.data));
window.location = "/";
}
//components/AddFood
import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
const AddFood = () => {
const [username, setUsername] = useState("");
const [description, setDescription] = useState("");
const [calories, setCalories] = useState("");
const [date, setDate] = useState(new Date());
const [users, setUsers] = useState([]);
const userInputRef = useRef("userInput");
useEffect(() => {
axios
.get("http://localhost:5000/users/")
.then((response) => {
if (response.data.length > 0) {
setUsers(response.data.map((user) => user.username));
setUsername(response.data[0].username);
}
})
.catch((error) => {
console.log(error);
});
}, []);
function handleUsername(e) {
setUsername(e.target.value);
}
function handleDescription(e) {
setDescription(e.target.value);
}
function handleCalories(e) {
setCalories(e.target.value);
}
function handleDate(date) {
setDate(date);
}
function handleSubmit(e) {
e.preventDefault();
const meal = {
username,
description,
calories,
date,
};
console.log(meal);
axios
.post("http://localhost:5000/calorie/add", meal)
.then((res) => console.log(res.data));
window.location = "/";
}
return (
<>
<div className="container">
<div className="card border-0 shadow my-4">
<div className="card-body p-3"></div>
<div>
<h3 style={{ textAlign: "center" }}>
<img
src="https://user-images.githubusercontent.com/37651620/142764215-78f5b75f-4871-451e-9a4d-dd77cc667fc5.png"
alt="Food"
style={{ height: "150px" }}
/>{" "}
</h3>
<form onSubmit={handleSubmit}>
<div
className="form-group"
style={{
marginLeft: "20px",
marginBottom: "15px",
marginRight: "20px",
}}
>
<label>👤 User name: </label>
<select
ref={userInputRef}
required
className="form-control"
value={username}
onChange={handleUsername}
>
{users.map(function (user) {
return (
<option key={user} value={user}>
{user}
</option>
);
})}
</select>
</div>
<div
className="form-group"
style={{
marginLeft: "20px",
marginBottom: "25px",
marginRight: "20px",
}}
>
<label>🥡 Food Info: </label>
<input
type="text"
required
className="form-control"
value={description}
onChange={handleDescription}
/>
</div>
<div
className="form-group"
style={{
marginLeft: "20px",
marginBottom: "15px",
marginRight: "20px",
}}
>
<label>🔥 Calories: </label>
<input
type="text"
className="form-control"
value={calories}
onChange={handleCalories}
/>
</div>
<div
className="form-group"
style={{
marginLeft: "20px",
marginBottom: "15px",
marginRight: "20px",
}}
>
<div style={{ textAlign: "center", cursor: "pointer" }}>
<label>Date: </label>
<div>
<DatePicker selected={date} onChange={handleDate} />
</div>
</div>
</div>
<div className="form-group" style={{ textAlign: "center" }}>
<input
type="submit"
value="Add Meal"
className="btn"
style={{
color: "white",
backgroundColor: "#8661d1",
marginBottom: "25px",
}}
/>
</div>
</form>
</div>
</div>
</div>
</>
);
};
export default AddFood;
//components/AddUser
import React, { useState } from "react";
import axios from "axios";
const AddUser = () => {
const [username, setUsername] = useState("");
function handleUsername(e) {
setUsername(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
const user = {
username,
};
console.log(user);
axios
.post("http://localhost:5000/users/add", user)
.then((res) => console.log(res.data));
setUsername("");
}
return (
<>
<div class="container">
<div class="card border-0 shadow my-4">
<div class="card-body p-3"></div>
<div>
<h3 style={{ textAlign: "center", marginBottom: "15px" }}>
<img
src="https://user-images.githubusercontent.com/37651620/142767072-ff777861-7ee9-4355-b48e-a624e8de085b.png"
alt="Logo"
style={{ height: "150px" }}
/>
</h3>
<form onSubmit={handleSubmit}>
<div
className="form-group"
style={{
marginLeft: "20px",
marginBottom: "15px",
marginRight: "20px",
}}
>
<label>👤 User name:</label>
<input
type="text"
required
className="form-control"
value={username}
onChange={handleUsername}
/>
</div>
<div
className="form-group"
style={{
textAlign: "center",
}}
>
<input
type="submit"
value="Create User"
className="btn "
style={{
color: "white",
marginBottom: "25px",
backgroundColor: "#8661d1",
}}
/>
</div>
</form>
</div>
</div>
</div>
</>
);
};
export default AddUser;
//components/EditFood
import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
const EditFood = (props) => {
const [username, setUsername] = useState("");
const [description, setDescription] = useState("");
const [calories, setCalories] = useState("");
const [date, setDate] = useState(new Date());
const [users, setUsers] = useState([]);
const userInputRef = useRef("userInput");
useEffect(() => {
axios
.get("http://localhost:5000/calorie/" + props.match.params.id)
.then((response) => {
setUsername(response.data.username);
setDescription(response.data.description);
setCalories(response.data.calories);
setDate(new Date(response.data.date));
})
.catch((error) => {
console.log(error);
});
axios
.get("http://localhost:5000/users/")
.then((response) => {
if (response.data.length > 0) {
setUsers(response.data.map((user) => user.username));
setUsername(response.data[0].username);
}
})
.catch((error) => {
console.log(error);
});
}, [props.match.params.id]);
function handleUsername(e) {
setUsername(e.target.value);
}
function handleDescription(e) {
setDescription(e.target.value);
}
function handleCalories(e) {
setCalories(e.target.value);
}
function handleDate(date) {
setDate(date);
}
function handleSubmit(e) {
e.preventDefault();
const food = {
username,
description,
calories,
date,
};
console.log(food);
axios
.post("http://localhost:5000/calorie/update", food)
.then((res) => console.log(res.data));
window.location = "/";
}
return (
<>
<div className="container">
<div className="card border-0 shadow my-4">
<div className="card-body p-3"></div>
<div>
<h3 style={{ textAlign: "center" }}>
<img
src="https://user-images.githubusercontent.com/37651620/142764215-78f5b75f-4871-451e-9a4d-dd77cc667fc5.png"
alt="Food"
style={{ height: "150px" }}
/>{" "}
</h3>
<form onSubmit={handleSubmit}>
<div
className="form-group"
style={{
marginLeft: "20px",
marginBottom: "15px",
marginRight: "20px",
}}
>
<label>👤 User name: </label>
<select
ref={userInputRef}
required
className="form-control"
value={username}
onChange={handleUsername}
>
{users.map(function (user) {
return (
<option key={user} value={user}>
{user}
</option>
);
})}
</select>
</div>
<div
className="form-group"
style={{
marginLeft: "20px",
marginBottom: "25px",
marginRight: "20px",
}}
>
<label>🥡 Food Info: </label>
<input
type="text"
required
className="form-control"
value={description}
onChange={handleDescription}
/>
</div>
<div
className="form-group"
style={{
marginLeft: "20px",
marginBottom: "15px",
marginRight: "20px",
}}
>
<label>🔥 Calories: </label>
<input
type="text"
className="form-control"
value={calories}
onChange={handleCalories}
/>
</div>
<div
className="form-group"
style={{
marginLeft: "20px",
marginBottom: "15px",
marginRight: "20px",
}}
>
<div style={{ textAlign: "center", cursor: "pointer" }}>
<label>Date: </label>
<div>
<DatePicker selected={date} onChange={handleDate} />
</div>
</div>
</div>
<div className="form-group" style={{ textAlign: "center" }}>
<input
type="submit"
value="Add Meal"
className="btn"
style={{
color: "white",
backgroundColor: "#8661d1",
marginBottom: "25px",
}}
/>
</div>
</form>
</div>
</div>
</div>
</>
);
};
export default EditFood;
//components/UserChart.js
import React, { useEffect, useState } from "react";
import { Pie } from "react-chartjs-2";
import axios from "axios";
const Delayed = ({ children, waitBeforeShow = 4500 }) => {
const [isShown, setIsShown] = useState(false);
useEffect(() => {
setTimeout(() => {
setIsShown(true);
}, waitBeforeShow);
}, [waitBeforeShow]);
return isShown ? children : null;
};
const UserChart = () => {
const [chartData, setChartData] = useState({});
async function getData() {
let username = [];
let calories = [];
await axios
.get("http://localhost:5000/calorie/")
.then((res) => {
console.log(res);
for (const dataObj of res.data) {
username.push(dataObj.username);
calories.push(parseInt(dataObj.calories));
console.log(username, calories);
}
setChartData({
labels: username,
datasets: [
{
label: "Calories",
data: calories,
backgroundColor: [
"#f42f42",
"#5ab950",
"#fe812a",
"#ffc748",
"#6b71c7",
"#8661d1",
"#8a2cba",
],
borderColor: [
"#f42f42",
"#5ab950",
"#fe812a",
"#ffc748",
"#6b71c7",
"#8661d1",
"#8a2cba",
],
borderWidth: 2,
},
],
});
})
.catch((err) => {
console.log(err);
});
console.log(username, calories);
}
useEffect(() => {
getData();
}, []);
return (
<div className="App">
<div>
<h5
style={{
fontSize: "20",
textAlign: "center",
marginTop: "1em",
marginBottom: "1em",
}}
>
Calorie per user
</h5>
<Delayed>
<Pie
data={chartData}
options={{
title: "{"
text: "Calorie per User",
fontSize: 10,
fontColor: "#212529",
},
maintainAspectRatio: true,
}}
/>
</Delayed>
</div>
</div>
);
};
export default UserChart;
//components/CalorieChart
import React, { useEffect, useState } from "react";
import { Bar } from "react-chartjs-2";
import axios from "axios";
const Delayed = ({ children, waitBeforeShow = 4500 }) => {
const [isShown, setIsShown] = useState(false);
useEffect(() => {
setTimeout(() => {
setIsShown(true);
}, waitBeforeShow);
}, [waitBeforeShow]);
return isShown ? children : null;
};
const CalorieChart = () => {
const [chartData, setChartData] = useState({});
async function getData() {
let foodCal = [];
let caloriesCal = [];
await axios
.get("http://localhost:5000/calorie/")
.then((res) => {
console.log(res);
for (let dataObj of res.data) {
foodCal.push(dataObj.description);
caloriesCal.push(parseInt(dataObj.caloriesCal));
console.log("foodCal, caloriesCal", foodCal, caloriesCal);
}
setChartData({
labels: foodCal,
datasets: [
{
label: "Cal",
data: caloriesCal,
backgroundColor: [
"#f42f42",
"#5ab950",
"#fe812a",
"#ffc748",
"#6b71c7",
"#8661d1",
"#8a2cba",
],
},
],
});
})
.catch((err) => {
console.log(err);
});
}
useEffect(() => {
getData();
}, []);
return (
<div className="App">
<h4>Food Analytics</h4>
<h5
style={{
fontSize: "20",
textAlign: "center",
marginBottom: "1em",
}}
>
Calorie Intake per each Food
</h5>
<div>
<Delayed>
<Bar
data={chartData}
options={{
responsive: true,
title: "{"
text: "Calorie Per Food ",
fontSize: 20,
fontColor: "#212529",
},
scales: {
yAxes: [
{
ticks: {
autoSkip: true,
maxTicksLimit: 10,
beginAtZero: true,
},
gridLines: {
// display: true,
},
},
],
xAxes: [
{
gridLines: {
display: true,
},
},
],
},
}}
/>
</Delayed>
</div>
</div>
);
};
export default CalorieChart;
//components/DisplayFoodList
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import CalorieChart from "../CalorieChart";
import UserChart from "../UserChart";
const FoodTrack = (props) => (
<tr>
<td>
<Link to={"/edit/" + props.meal._id} style={{ color: " #a04949" }}>
<img
src="https://user-images.githubusercontent.com/37651620/142769270-6128d45e-3650-4b66-bc0b-a76e3991fa1f.png"
alt="edit"
style={{ height: "40px" }}
/>
</Link>{" "}
|{" "}
<a
href="#"
onClick={() => {
props.deleteMeal(props.meal._id);
window.location.reload(false);
}}
style={{ color: " #a04949" }}
>
<img
src="https://user-images.githubusercontent.com/37651620/142769328-23d55107-8bed-4fa0-92b8-cca7df931083.png"
alt="edit"
style={{ height: "40px" }}
/>
</a>
</td>
<td>{props.meal.username}</td>
<td>{props.meal.description}</td>
<td>{props.meal.calories}</td>
<td>{props.meal.date.substring(0, 10)}</td>
</tr>
);
const DisplayFoodList = () => {
const [foods, setFoods] = useState([]);
useEffect(() => {
axios
.get("http://localhost:5000/calorie/")
.then((response) => {
setFoods(response.data);
})
.catch((error) => {
console.log(error);
});
}, []);
function deleteMeal(id) {
axios.delete("http://localhost:5000/calorie/" + id).then((response) => {
console.log(response.data);
});
setFoods(foods.filter((el) => el._id !== id));
}
const mealList = () => {
return foods.map((currentmeal) => {
return (
<FoodTrack
meal={currentmeal}
deleteMeal={deleteMeal}
key={currentmeal._id}
/>
);
});
};
return (
<>
<>
<div className="container">
<div className="card border-0 shadow my-4">
<div className="card-body p-5">
<h3 style={{ textAlign: "center", marginBottom: "15px" }}>
Calorie Journal
</h3>
<table className="table" style={{ textAlign: "center" }}>
<thead className="thead" style={{ backgroundColor: "#8661d1" }}>
<tr>
<th>Edit/Delete</th>
<th>👤 Username</th>
<th>📙 Description</th>
<th>🔥 Calories</th>
<th>📅 Date</th>
</tr>
</thead>
<tbody>{mealList()}</tbody>
</table>
</div>
</div>
</div>
<div className="container">
<div
className="card border-0 shadow my-2"
style={{ padding: "2rem" }}
>
<div className="card-body p-1"></div>
<UserChart />
<CalorieChart />
</div>
</div>
</>
</>
);
};
export default DisplayFoodList;