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

Food App Case Study | Mradul Rathore #41

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
130 changes: 130 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
30 changes: 30 additions & 0 deletions Mradul-Rathore-Food-App-Case-Study/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Problem Statement

It is known fact that in today’s work-from-home world, people prefer ordering food that can be delivered at the comfort of their home. So most of the times people end up ordering food from restaurants that have delivery services. The objective of this problem statement is to come up with a solution for people to order food online and get prompt delivery. You need to solve the given problem by developing a web application, that should facilitate users to order food online from different restaurants using the web-app to cater their needs.

# Scope of work

You have been asked to build the backend system for the following:
- Registration
- Login and
- Display the list of Food items

## API Endpoints

- /api/register
- To register the user with basic
details
- /api/authenticate
- To validate the user is registered in the system
- /api/users
- To get all the users who are registered to the system, the end point should return an array
- /api/users/:userID
- To return user by specifying id
- /api/users
- Should update the user specified in the payload which shall match the ID and updated the existing user with the new details
- /api/users/:userID
- Should delete the user which is specified in the :userID
- /api/food
- To add a new food to the system
- /api/food/:foodID
- To return a food item specified with :foodID
11 changes: 11 additions & 0 deletions Mradul-Rathore-Food-App-Case-Study/app/config/db.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;

const db = {};
db.mongoose = mongoose;
db.url = process.env.MONGO_URI;
db.users = require("../models/user.model")(mongoose);
db.foods = require("../models/food.model")(mongoose);
db.port = process.env.PORT

module.exports = db;
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const db = require("../config/db.config")
const Food = db.foods;

//register user
exports.addFood = async (req, res) => {

try {
// Get user input
const { foodId, foodName, foodCost, foodType } = req.body;

// Validate food type
if (foodType != "Indian" && foodType != "Mexican" && foodType != "Chinese") {
res.status(400).send("Food type is not valid. Valide types: Indian/Mexican/Chinese");
}

// check if food already exist
// Validate if food exist in our database
const oldFood = await Food.findOne({ foodId });

if (oldFood) {
return res.status(409).send("Food Already Exist.");
}

// Create food in our database
const food = await Food.create({
foodId: foodId,
foodName: foodName,
foodCost: foodCost,
foodType: foodType,
});

// return new food
res.status(201).json(food);
} catch (err) {
console.log(err);
}
};

//fetch food by id
exports.fetchFoodById = async (req, res) => {
const foodId = req.params.id;

const food = await Food.findOne({ foodId });

if (!food)
res.status(404).send({ message: "Sorry Food Not Found" })
else
res.send(food);
}


159 changes: 159 additions & 0 deletions Mradul-Rathore-Food-App-Case-Study/app/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
const db = require("../config/db.config")

const { registerationValidation } = require('../../validation')
const User = db.users;
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")

//register user
exports.registerUser = async (req, res) => {

try {
// Validate user input
const { error } = registerationValidation(req.body)
if (error) {
return res.status(400).send(error.details[0].message)
}

// Get user input
const { username, email, password, address } = req.body;

// check if user already exist
// Validate if user exist in our database
const oldUser = await User.findOne({ email });

if (oldUser) {
return res.status(409).send("User Already Exist. Please Login");
}

//Encrypt user password
encryptedPassword = await bcrypt.hash(password, 10);

// Create user in our database
const user = await User.create({
username: username,
email: email.toLowerCase(), // sanitize: convert email to lowercase
password: encryptedPassword,
address: address
});

// Create token
const token = jwt.sign(
{ user_id: user._id, email },
process.env.TOKEN_KEY,
{
expiresIn: "24h",
}
);
// save user token
user.token = token;

// return new user
res.status(201).json(user);
} catch (err) {
console.log(err);
}
};

//authenticate user
exports.authenticate = async (req, res) => {
// Our login logic starts here
try {
// Get user input
const { email, password } = req.body;

// Validate user input
if (!(email && password)) {
res.status(400).send("All input is required");
}

// Validate if user exist in our database
const user = await User.findOne({ email });

if (user && (await bcrypt.compare(password, user.password))) {
// Create token
const token = jwt.sign(
{ user_id: user._id, email },
process.env.TOKEN_KEY,
{
expiresIn: "24h",
}
);

// save user token
user.token = token;

const sucessMessage = {
message: "user logged in successful"
}
// user
res.status(200).json(sucessMessage);
}
res.status(403).send("Forbidden");
} catch (err) {
console.log(err);
}
}

//fetch all users
exports.fetchAllUsers = (req, res) => {
User.find().then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "error while retrieving the users."
})
})
}

//fetch user by id
exports.fetchUserById = (req, res) => {
const id = req.params.id;
User.findById(id).then(
data => {
if (!data)
res.status(404).send({ message: "Sorry user With " + id + " not found" });
else
res.send(data);
}
).catch(err => {
res.status(500).send({
message: err.message || "error while retrieving the user with id " + id
})
})
}

//update user by id
exports.updateUserById = (req, res) => {
const id = req.body.id;

User.findOneAndUpdate({ _id: id }, req.body).then(function (user) {
User.findOne({ _id: id }).then(function (user) {
if (!user)
res.status(404).send({ message: "Sorry user with " + id + " not found" });
else
res.status(200).json(user);
})
}).catch(err => {
res.status(500).send({
message: err.message || "error updating the user with id " + id
})
})
}

//delete user by id
exports.deleteUserById = (req, res) => {
const id = req.params.id;
User.findByIdAndRemove(id, { useFindAndModify: false }).then(
data => {
if (!data)
res.status(404).send({ message: "Sorry user with " + id + " not found" });
else
res.send({ message: "User deleted successfully" });
}
).catch(err => {
res.status(500).send({
message: err.message || "error deleting the user with id " + id
})
})
}
Loading