Initial Commit · TeeCDP/Nodejs-REST-API@4635921 · GitHub
Skip to content

Commit 4635921

Browse files
committed
Initial Commit
0 parents  commit 4635921

11 files changed

Lines changed: 919 additions & 0 deletions

File tree

.env

Lines changed: 5 additions & 0 deletions

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

Controllers/Product.Controller.js

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
const createError = require('http-errors');
2+
const mongoose = require('mongoose');
3+
4+
const Product = require('../Models/Product.model');
5+
6+
module.exports = {
7+
getAllProducts: async (req, res, next) => {
8+
try {
9+
const results = await Product.find({}, { __v: 0 });
10+
// const results = await Product.find({}, { name: 1, price: 1, _id: 0 });
11+
// const results = await Product.find({ price: 699 }, {});
12+
res.send(results);
13+
} catch (error) {
14+
console.log(error.message);
15+
}
16+
},
17+
18+
createNewProduct: async (req, res, next) => {
19+
try {
20+
const product = new Product(req.body);
21+
const result = await product.save();
22+
res.send(result);
23+
} catch (error) {
24+
console.log(error.message);
25+
if (error.name === 'ValidationError') {
26+
next(createError(422, error.message));
27+
return;
28+
}
29+
next(error);
30+
}
31+
32+
/*Or:
33+
If you want to use the Promise based approach*/
34+
/*
35+
const product = new Product({
36+
name: req.body.name,
37+
price: req.body.price
38+
});
39+
product
40+
.save()
41+
.then(result => {
42+
console.log(result);
43+
res.send(result);
44+
})
45+
.catch(err => {
46+
console.log(err.message);
47+
});
48+
*/
49+
},
50+
51+
findProductById: async (req, res, next) => {
52+
const id = req.params.id;
53+
try {
54+
const product = await Product.findById(id);
55+
// const product = await Product.findOne({ _id: id });
56+
if (!product) {
57+
throw createError(404, 'Product does not exist.');
58+
}
59+
res.send(product);
60+
} catch (error) {
61+
console.log(error.message);
62+
if (error instanceof mongoose.CastError) {
63+
next(createError(400, 'Invalid Product id'));
64+
return;
65+
}
66+
next(error);
67+
}
68+
},
69+
70+
updateAProduct: async (req, res, next) => {
71+
try {
72+
const id = req.params.id;
73+
const updates = req.body;
74+
const options = { new: true };
75+
76+
const result = await Product.findByIdAndUpdate(id, updates, options);
77+
if (!result) {
78+
throw createError(404, 'Product does not exist');
79+
}
80+
res.send(result);
81+
} catch (error) {
82+
console.log(error.message);
83+
if (error instanceof mongoose.CastError) {
84+
return next(createError(400, 'Invalid Product Id'));
85+
}
86+
87+
next(error);
88+
}
89+
},
90+
91+
deleteAProduct: async (req, res, next) => {
92+
const id = req.params.id;
93+
try {
94+
const result = await Product.findByIdAndDelete(id);
95+
// console.log(result);
96+
if (!result) {
97+
throw createError(404, 'Product does not exist.');
98+
}
99+
res.send(result);
100+
} catch (error) {
101+
console.log(error.message);
102+
if (error instanceof mongoose.CastError) {
103+
next(createError(400, 'Invalid Product id'));
104+
return;
105+
}
106+
next(error);
107+
}
108+
}
109+
};

Models/Product.model.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const mongoose = require('mongoose');
2+
const Schema = mongoose.Schema;
3+
4+
const ProductSchema = new Schema({
5+
name: {
6+
type: String,
7+
required: true
8+
},
9+
price: {
10+
type: Number,
11+
required: true
12+
}
13+
});
14+
15+
const Product = mongoose.model('product', ProductSchema);
16+
module.exports = Product;

README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# RESTful API
2+
3+
This is a RESTful API example based on Node.js and MongoDB, following the **MVC pattern** i.e. Model ~~View~~ Controller.
4+
5+
**Mongoose** is used for Database transactions which is an elegant solution to mongodb object modeling for node.js.
6+
7+
The application is **production ready**, and can be used behind a Nginx reverse proxy securely.
8+
9+
---
10+
11+
#### To start setting up the project
12+
13+
Step 1: Clone the repo
14+
15+
```bash
16+
git clone https://github.com/trulymittal/RESTful-API.git
17+
```
18+
19+
Step 2: cd into the cloned repo and run:
20+
21+
```bash
22+
npm install
23+
```
24+
25+
Step 3: Put your credentials in the .env file.
26+
27+
```bash
28+
PORT=3000
29+
MONGODB_URI=
30+
DB_NAME=
31+
DB_USER=
32+
DB_PASS=
33+
```
34+
35+
Step 4: Start the API by
36+
37+
```bash
38+
npm start
39+
```
40+
41+
## Author
42+
43+
- [**Truly Mittal**](https://trulymittal.com)
44+
45+
## License
46+
47+
This project is licensed under the MIT License.

Routes/Product.route.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const express = require('express');
2+
const router = express.Router();
3+
4+
const ProductController = require('../Controllers/Product.Controller');
5+
6+
//Get a list of all products
7+
router.get('/', ProductController.getAllProducts);
8+
9+
//Create a new product
10+
router.post('/', ProductController.createNewProduct);
11+
12+
//Get a product by id
13+
router.get('/:id', ProductController.findProductById);
14+
15+
//Update a product by id
16+
router.patch('/:id', ProductController.updateAProduct);
17+
18+
//Delete a product by id
19+
router.delete('/:id', ProductController.deleteAProduct);
20+
21+
module.exports = router;

app.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const express = require('express');
2+
const createError = require('http-errors');
3+
const dotenv = require('dotenv').config();
4+
5+
const app = express();
6+
7+
app.use(express.json());
8+
app.use(express.urlencoded({ extended: true }));
9+
10+
// Initialize DB
11+
require('./initDB')();
12+
13+
const ProductRoute = require('./Routes/Product.route');
14+
app.use('/products', ProductRoute);
15+
16+
//404 handler and pass to error handler
17+
app.use((req, res, next) => {
18+
/*
19+
const err = new Error('Not found');
20+
err.status = 404;
21+
next(err);
22+
*/
23+
// You can use the above code if your not using the http-errors module
24+
next(createError(404, 'Not found'));
25+
});
26+
27+
//Error handler
28+
app.use((err, req, res, next) => {
29+
res.status(err.status || 500);
30+
res.send({
31+
error: {
32+
status: err.status || 500,
33+
message: err.message
34+
}
35+
});
36+
});
37+
38+
const PORT = process.env.PORT || 3000;
39+
40+
app.listen(PORT, () => {
41+
console.log('Server started on port ' + PORT + '...');
42+
});

initDB.js

Lines changed: 38 additions & 0 deletions

0 commit comments

Comments
 (0)