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

13-controllers #25

Open
wants to merge 17 commits into
base: 01-basic-setup
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
node_modules
node_modules
nodemon.json
uploads
12 changes: 11 additions & 1 deletion README.MD
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Creating a RESTful API with Node.js
This repository accompanies my YouTube video series on building a RESTful API with Node.js
This repository accompanies my YouTube video series on building a RESTful API with Node.js: [https://github.com/academind/node-restful-api-tutorial.git](https://github.com/academind/node-restful-api-tutorial.git)

## Usage
Check out the branch you're interested in (i.e. which belongs to the video in my series you just watched), ```git clone``` it and thereafter run ```npm install```.

Make sure to also add your Mongo Atlas Admin Username to a nodemon.json file (which you have to create).

```
{
"env": {
"MONGO_ATLAS_PW": "YOUR_MONGO_USER_PW"
}
}
```
115 changes: 115 additions & 0 deletions api/controllers/orders.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
const mongoose = require("mongoose");

const Order = require("../models/order");
const Product = require("../models/product");

exports.orders_get_all = (req, res, next) => {
Order.find()
.select("product quantity _id")
.populate("product", "name")
.exec()
.then(docs => {
res.status(200).json({
count: docs.length,
orders: docs.map(doc => {
return {
_id: doc._id,
product: doc.product,
quantity: doc.quantity,
request: {
type: "GET",
url: "http://localhost:3000/orders/" + doc._id
}
};
})
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
};

exports.orders_create_order = (req, res, next) => {
Product.findById(req.body.productId)
.then(product => {
if (!product) {
return res.status(404).json({
message: "Product not found"
});
}
const order = new Order({
_id: mongoose.Types.ObjectId(),
quantity: req.body.quantity,
product: req.body.productId
});
return order.save();
})
.then(result => {
console.log(result);
res.status(201).json({
message: "Order stored",
createdOrder: {
_id: result._id,
product: result.product,
quantity: result.quantity
},
request: {
type: "GET",
url: "http://localhost:3000/orders/" + result._id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};

exports.orders_get_order = (req, res, next) => {
Order.findById(req.params.orderId)
.populate("product")
.exec()
.then(order => {
if (!order) {
return res.status(404).json({
message: "Order not found"
});
}
res.status(200).json({
order: order,
request: {
type: "GET",
url: "http://localhost:3000/orders"
}
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
};

exports.orders_delete_order = (req, res, next) => {
Order.remove({ _id: req.params.orderId })
.exec()
.then(result => {
res.status(200).json({
message: "Order deleted",
request: {
type: "POST",
url: "http://localhost:3000/orders",
body: { productId: "ID", quantity: "Number" }
}
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
};
144 changes: 144 additions & 0 deletions api/controllers/products.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
const mongoose = require("mongoose");
const Product = require("../models/product");

exports.products_get_all = (req, res, next) => {
Product.find()
.select("name price _id productImage")
.exec()
.then(docs => {
const response = {
count: docs.length,
products: docs.map(doc => {
return {
name: doc.name,
price: doc.price,
productImage: doc.productImage,
_id: doc._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + doc._id
}
};
})
};
// if (docs.length >= 0) {
res.status(200).json(response);
// } else {
// res.status(404).json({
// message: 'No entries found'
// });
// }
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};

exports.products_create_product = (req, res, next) => {
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price,
productImage: req.file.path
});
product
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Created product successfully",
createdProduct: {
name: result.name,
price: result.price,
_id: result._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + result._id
}
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};

exports.products_get_product = (req, res, next) => {
const id = req.params.productId;
Product.findById(id)
.select("name price _id productImage")
.exec()
.then(doc => {
console.log("From database", doc);
if (doc) {
res.status(200).json({
product: doc,
request: {
type: "GET",
url: "http://localhost:3000/products"
}
});
} else {
res
.status(404)
.json({ message: "No valid entry found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};

exports.products_update_product = (req, res, next) => {
const id = req.params.productId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Product.update({ _id: id }, { $set: updateOps })
.exec()
.then(result => {
res.status(200).json({
message: "Product updated",
request: {
type: "GET",
url: "http://localhost:3000/products/" + id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};

exports.products_delete = (req, res, next) => {
const id = req.params.productId;
Product.remove({ _id: id })
.exec()
.then(result => {
res.status(200).json({
message: "Product deleted",
request: {
type: "POST",
url: "http://localhost:3000/products",
body: { name: "String", price: "Number" }
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
105 changes: 105 additions & 0 deletions api/controllers/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");

const User = require("../models/user");

exports.user_signup = (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
});
};

exports.user_login = (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length < 1) {
return res.status(401).json({
message: "Auth failed"
});
}
bcrypt.compare(req.body.password, user[0].password, (err, result) => {
if (err) {
return res.status(401).json({
message: "Auth failed"
});
}
if (result) {
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn: "1h"
}
);
return res.status(200).json({
message: "Auth successful",
token: token
});
}
res.status(401).json({
message: "Auth failed"
});
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};

exports.user_delete = (req, res, next) => {
User.remove({ _id: req.params.userId })
.exec()
.then(result => {
res.status(200).json({
message: "User deleted"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
Loading