Skip to content

Commit 8260dc6

Browse files
committed
rebuild for deploying to Heroku & work with ClearDB
0 parents  commit 8260dc6

File tree

9 files changed

+327
-0
lines changed

9 files changed

+327
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules
2+
package-lock.json

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Node.js Rest APIs with Express & MySQL example
2+
3+
For more detail, please visit:
4+
> [Build Node.js Rest APIs with Express & MySQL](https://bezkoder.com/node-js-rest-api-express-mysql/)
5+
6+
> [Deploying/Hosting Node.js app on Heroku with MySQL database](https://bezkoder.com/deploy-node-js-app-heroku-cleardb-mysql/)
7+
8+
## Project setup
9+
```
10+
npm install
11+
```
12+
13+
### Run
14+
```
15+
node server.js
16+
```

app/config/db.config.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
module.exports = {
2+
HOST: "us-cdbr-iron-east-02.cleardb.net",
3+
USER: "b7e24378878xxx",
4+
PASSWORD: "0200exxx",
5+
DB: "heroku_7643ec736354xxx"
6+
};
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
const Customer = require("../models/customer.model.js");
2+
3+
// Create and Save a new Customer
4+
exports.create = (req, res) => {
5+
// Validate request
6+
if (!req.body) {
7+
res.status(400).send({
8+
message: "Content can not be empty!"
9+
});
10+
}
11+
12+
// Create a Customer
13+
const customer = new Customer({
14+
email: req.body.email,
15+
name: req.body.name,
16+
active: req.body.active
17+
});
18+
19+
// Save Customer in the database
20+
Customer.create(customer, (err, data) => {
21+
if (err)
22+
res.status(500).send({
23+
message:
24+
err.message || "Some error occurred while creating the Customer."
25+
});
26+
else res.send(data);
27+
});
28+
};
29+
30+
// Retrieve all Customers from the database.
31+
exports.findAll = (req, res) => {
32+
Customer.getAll((err, data) => {
33+
if (err)
34+
res.status(500).send({
35+
message:
36+
err.message || "Some error occurred while retrieving customers."
37+
});
38+
else res.send(data);
39+
});
40+
};
41+
42+
// Find a single Customer with a customerId
43+
exports.findOne = (req, res) => {
44+
Customer.findById(req.params.customerId, (err, data) => {
45+
if (err) {
46+
if (err.kind === "not_found") {
47+
res.status(404).send({
48+
message: `Not found Customer with id ${req.params.customerId}.`
49+
});
50+
} else {
51+
res.status(500).send({
52+
message: "Error retrieving Customer with id " + req.params.customerId
53+
});
54+
}
55+
} else res.send(data);
56+
});
57+
};
58+
59+
// Update a Customer identified by the customerId in the request
60+
exports.update = (req, res) => {
61+
// Validate Request
62+
if (!req.body) {
63+
res.status(400).send({
64+
message: "Content can not be empty!"
65+
});
66+
}
67+
68+
console.log(req.body);
69+
70+
Customer.updateById(
71+
req.params.customerId,
72+
new Customer(req.body),
73+
(err, data) => {
74+
if (err) {
75+
if (err.kind === "not_found") {
76+
res.status(404).send({
77+
message: `Not found Customer with id ${req.params.customerId}.`
78+
});
79+
} else {
80+
res.status(500).send({
81+
message: "Error updating Customer with id " + req.params.customerId
82+
});
83+
}
84+
} else res.send(data);
85+
}
86+
);
87+
};
88+
89+
// Delete a Customer with the specified customerId in the request
90+
exports.delete = (req, res) => {
91+
Customer.remove(req.params.customerId, (err, data) => {
92+
if (err) {
93+
if (err.kind === "not_found") {
94+
res.status(404).send({
95+
message: `Not found Customer with id ${req.params.customerId}.`
96+
});
97+
} else {
98+
res.status(500).send({
99+
message: "Could not delete Customer with id " + req.params.customerId
100+
});
101+
}
102+
} else res.send({ message: `Customer was deleted successfully!` });
103+
});
104+
};
105+
106+
// Delete all Customers from the database.
107+
exports.deleteAll = (req, res) => {
108+
Customer.removeAll((err, data) => {
109+
if (err)
110+
res.status(500).send({
111+
message:
112+
err.message || "Some error occurred while removing all customers."
113+
});
114+
else res.send({ message: `All Customers were deleted successfully!` });
115+
});
116+
};

app/models/customer.model.js

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
const sql = require("./db.js");
2+
3+
// constructor
4+
const Customer = function(customer) {
5+
this.email = customer.email;
6+
this.name = customer.name;
7+
this.active = customer.active;
8+
};
9+
10+
Customer.create = (newCustomer, result) => {
11+
sql.query("INSERT INTO customers SET ?", newCustomer, (err, res) => {
12+
if (err) {
13+
console.log("error: ", err);
14+
result(err, null);
15+
return;
16+
}
17+
18+
console.log("created customer: ", { id: res.insertId, ...newCustomer });
19+
result(null, { id: res.insertId, ...newCustomer });
20+
});
21+
};
22+
23+
Customer.findById = (customerId, result) => {
24+
sql.query(`SELECT * FROM customers WHERE id = ${customerId}`, (err, res) => {
25+
if (err) {
26+
console.log("error: ", err);
27+
result(err, null);
28+
return;
29+
}
30+
31+
if (res.length) {
32+
console.log("found customer: ", res[0]);
33+
result(null, res[0]);
34+
return;
35+
}
36+
37+
// not found Customer with the id
38+
result({ kind: "not_found" }, null);
39+
});
40+
};
41+
42+
Customer.getAll = result => {
43+
sql.query("SELECT * FROM customers", (err, res) => {
44+
if (err) {
45+
console.log("error: ", err);
46+
result(null, err);
47+
return;
48+
}
49+
50+
console.log("customers: ", res);
51+
result(null, res);
52+
});
53+
};
54+
55+
Customer.updateById = (id, customer, result) => {
56+
sql.query(
57+
"UPDATE customers SET email = ?, name = ?, active = ? WHERE id = ?",
58+
[customer.email, customer.name, customer.active, id],
59+
(err, res) => {
60+
if (err) {
61+
console.log("error: ", err);
62+
result(null, err);
63+
return;
64+
}
65+
66+
if (res.affectedRows == 0) {
67+
// not found Customer with the id
68+
result({ kind: "not_found" }, null);
69+
return;
70+
}
71+
72+
console.log("updated customer: ", { id: id, ...customer });
73+
result(null, { id: id, ...customer });
74+
}
75+
);
76+
};
77+
78+
Customer.remove = (id, result) => {
79+
sql.query("DELETE FROM customers WHERE id = ?", id, (err, res) => {
80+
if (err) {
81+
console.log("error: ", err);
82+
result(null, err);
83+
return;
84+
}
85+
86+
if (res.affectedRows == 0) {
87+
// not found Customer with the id
88+
result({ kind: "not_found" }, null);
89+
return;
90+
}
91+
92+
console.log("deleted customer with id: ", id);
93+
result(null, res);
94+
});
95+
};
96+
97+
Customer.removeAll = result => {
98+
sql.query("DELETE FROM customers", (err, res) => {
99+
if (err) {
100+
console.log("error: ", err);
101+
result(null, err);
102+
return;
103+
}
104+
105+
console.log(`deleted ${res.affectedRows} customers`);
106+
result(null, res);
107+
});
108+
};
109+
110+
module.exports = Customer;

app/models/db.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const mysql = require("mysql");
2+
const dbConfig = require("../config/db.config.js");
3+
4+
var connection = mysql.createPool({
5+
host: dbConfig.HOST,
6+
user: dbConfig.USER,
7+
password: dbConfig.PASSWORD,
8+
database: dbConfig.DB
9+
});
10+
11+
module.exports = connection;

app/routes/customer.routes.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
module.exports = app => {
2+
const customers = require("../controllers/customer.controller.js");
3+
4+
// Create a new Customer
5+
app.post("/customers", customers.create);
6+
7+
// Retrieve all Customers
8+
app.get("/customers", customers.findAll);
9+
10+
// Retrieve a single Customer with customerId
11+
app.get("/customers/:customerId", customers.findOne);
12+
13+
// Update a Customer with customerId
14+
app.put("/customers/:customerId", customers.update);
15+
16+
// Delete a Customer with customerId
17+
app.delete("/customers/:customerId", customers.delete);
18+
19+
// Create a new Customer
20+
app.delete("/customers", customers.deleteAll);
21+
};

package.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"name": "nodejs-express-mysql",
3+
"version": "1.0.0",
4+
"description": "Node.js Restful CRUD API with Node.js, Express and MySQL",
5+
"main": "server.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"keywords": [
10+
"nodejs",
11+
"express",
12+
"mysql",
13+
"restapi"
14+
],
15+
"author": "bezkoder",
16+
"license": "ISC",
17+
"dependencies": {
18+
"body-parser": "^1.19.0",
19+
"express": "^4.17.1",
20+
"mysql": "^2.17.1"
21+
}
22+
}

server.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const express = require("express");
2+
const bodyParser = require("body-parser");
3+
4+
const app = express();
5+
6+
// parse requests of content-type - application/json
7+
app.use(bodyParser.json());
8+
9+
// parse requests of content-type - application/x-www-form-urlencoded
10+
app.use(bodyParser.urlencoded({ extended: true }));
11+
12+
// simple route
13+
app.get("/", (req, res) => {
14+
res.json({ message: "Welcome to bezkoder application." });
15+
});
16+
17+
require("./app/routes/customer.routes.js")(app);
18+
19+
// set port, listen for requests
20+
const PORT = process.env.PORT || 3000;
21+
app.listen(PORT, () => {
22+
console.log(`Server is running on port ${PORT}.`);
23+
});

0 commit comments

Comments
 (0)