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

09 image upload #16

Open
wants to merge 12 commits into
base: 01-basic-setup
Choose a base branch
from
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"
}
}
```
9 changes: 9 additions & 0 deletions api/models/order.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mongoose = require('mongoose');

const orderSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true },
quantity: { type: Number, default: 1 }
});

module.exports = mongoose.model('Order', orderSchema);
10 changes: 10 additions & 0 deletions api/models/product.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
price: { type: Number, required: true },
productImage: { type: String, required: true }
});

module.exports = mongoose.model('Product', productSchema);
120 changes: 120 additions & 0 deletions api/routes/orders.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");

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

// Handle incoming GET requests to /orders
router.get("/", (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
});
});
});

router.post("/", (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
});
});
});

router.get("/:orderId", (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
});
});
});

router.delete("/:orderId", (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
});
});
});

module.exports = router;
176 changes: 176 additions & 0 deletions api/routes/products.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const multer = require('multer');

const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
}
});

const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};

const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});

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

router.get("/", (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
});
});
});

router.post("/", upload.single('productImage'), (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
});
});
});

router.get("/:productId", (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 });
});
});

router.patch("/:productId", (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
});
});
});

router.delete("/:productId", (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
});
});
});

module.exports = router;
Loading