Skip to content

Commit f5f6c05

Browse files
committed
Nodejs PostgreSQL CRUD Example
1 parent 01da656 commit f5f6c05

File tree

8 files changed

+1031
-0
lines changed

8 files changed

+1031
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Copyright by https://loizenai.com
3+
* youtube loizenai
4+
*/
5+
6+
const env = require('./env.js');
7+
8+
const Sequelize = require('sequelize');
9+
const sequelize = new Sequelize(env.database, env.username, env.password, {
10+
host: env.host,
11+
dialect: env.dialect,
12+
operatorsAliases: false,
13+
14+
pool: {
15+
max: env.max,
16+
min: env.pool.min,
17+
acquire: env.pool.acquire,
18+
idle: env.pool.idle
19+
}
20+
});
21+
22+
const db = {};
23+
24+
db.Sequelize = Sequelize;
25+
db.sequelize = sequelize;
26+
27+
db.Customer = require('../models/customer.model.js')(sequelize, Sequelize);
28+
29+
module.exports = db;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* Copyright by https://loizenai.com
3+
* youtube loizenai
4+
*/
5+
6+
const env = {
7+
database: 'loizenaidb',
8+
username: 'postgres',
9+
password: '123',
10+
host: 'localhost',
11+
dialect: 'postgres',
12+
pool: {
13+
max: 5,
14+
min: 0,
15+
acquire: 30000,
16+
idle: 10000
17+
}
18+
};
19+
20+
module.exports = env;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
1+
/**
2+
* Copyright by https://loizenai.com
3+
* youtube loizenai
4+
*/
5+
6+
const db = require('../config/db.config.js');
7+
const Customer = db.Customer;
8+
9+
exports.create = (req, res) => {
10+
let customer = {};
11+
12+
try{
13+
// Building Customer object from upoading request's body
14+
customer.firstname = req.body.firstname;
15+
customer.lastname = req.body.lastname;
16+
customer.address = req.body.address;
17+
customer.age = req.body.age;
18+
19+
// Save to MySQL database
20+
Customer.create(customer).then(result => {
21+
// send uploading message to client
22+
res.status(200).json({
23+
message: "Upload Successfully a Customer with id = " + result.id,
24+
customer: result,
25+
});
26+
});
27+
}catch(error){
28+
res.status(500).json({
29+
message: "Fail!",
30+
error: error.message
31+
});
32+
}
33+
}
34+
35+
exports.retrieveAllCustomers = (req, res) => {
36+
// find all Customer information from
37+
Customer.findAll()
38+
.then(customerInfos => {
39+
res.status(200).json({
40+
message: "Get all Customers' Infos Successfully!",
41+
customers: customerInfos
42+
});
43+
})
44+
. catch(error => {
45+
// log on console
46+
console.log(error);
47+
48+
res.status(500).json({
49+
message: "Error!",
50+
error: error
51+
});
52+
});
53+
}
54+
55+
exports.getCustomerById = (req, res) => {
56+
// find all Customer information from
57+
let customerId = req.params.id;
58+
Customer.findByPk(customerId)
59+
.then(customer => {
60+
res.status(200).json({
61+
message: " Successfully Get a Customer with id = " + customerId,
62+
customers: customer
63+
});
64+
})
65+
. catch(error => {
66+
// log on console
67+
console.log(error);
68+
69+
res.status(500).json({
70+
message: "Error!",
71+
error: error
72+
});
73+
});
74+
}
75+
76+
77+
exports.filteringByAge = (req, res) => {
78+
let age = req.query.age;
79+
80+
Customer.findAll({
81+
attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyrightby'],
82+
where: {age: age}
83+
})
84+
.then(results => {
85+
res.status(200).json({
86+
message: "Get all Customers with age = " + age,
87+
customers: results,
88+
});
89+
})
90+
. catch(error => {
91+
console.log(error);
92+
res.status(500).json({
93+
message: "Error!",
94+
error: error
95+
});
96+
});
97+
}
98+
99+
exports.pagination = (req, res) => {
100+
try{
101+
let page = parseInt(req.query.page);
102+
let limit = parseInt(req.query.limit);
103+
104+
const offset = page ? page * limit : 0;
105+
106+
Customer.findAndCountAll({ limit: limit, offset:offset })
107+
.then(data => {
108+
const totalPages = Math.ceil(data.count / limit);
109+
const response = {
110+
message: "Paginating is completed! Query parameters: page = " + page + ", limit = " + limit,
111+
data: {
112+
"copyrightby": "https://loizenai.com",
113+
"totalItems": data.count,
114+
"totalPages": totalPages,
115+
"limit": limit,
116+
"currentPageNumber": page + 1,
117+
"currentPageSize": data.rows.length,
118+
"customers": data.rows
119+
}
120+
};
121+
res.send(response);
122+
});
123+
}catch(error) {
124+
res.status(500).send({
125+
message: "Error -> Can NOT complete a paging request!",
126+
error: error.message,
127+
});
128+
}
129+
}
130+
131+
exports.pagingfilteringsorting = (req, res) => {
132+
try{
133+
let page = parseInt(req.query.page);
134+
let limit = parseInt(req.query.limit);
135+
let age = parseInt(req.query.age);
136+
137+
const offset = page ? page * limit : 0;
138+
139+
console.log("offset = " + offset);
140+
141+
Customer.findAndCountAll({
142+
attributes: ['id', 'firstname', 'lastname', 'age', 'address'],
143+
where: {age: age},
144+
order: [
145+
['firstname', 'ASC'],
146+
['lastname', 'DESC']
147+
],
148+
limit: limit,
149+
offset:offset
150+
})
151+
.then(data => {
152+
const totalPages = Math.ceil(data.count / limit);
153+
const response = {
154+
message: "Pagination Filtering Sorting request is completed! Query parameters: page = " + page + ", limit = " + limit + ", age = " + age,
155+
data: {
156+
"copyrightby": "https://loizenai.com",
157+
"totalItems": data.count,
158+
"totalPages": totalPages,
159+
"limit": limit,
160+
"age-filtering": age,
161+
"currentPageNumber": page + 1,
162+
"currentPageSize": data.rows.length,
163+
"customers": data.rows
164+
}
165+
};
166+
res.send(response);
167+
});
168+
}catch(error) {
169+
res.status(500).send({
170+
message: "Error -> Can NOT complete a paging request!",
171+
error: error.message,
172+
});
173+
}
174+
}
175+
176+
exports.updateById = async (req, res) => {
177+
try{
178+
let customerId = req.params.id;
179+
let customer = await Customer.findByPk(customerId);
180+
181+
if(!customer){
182+
// return a response to client
183+
res.status(404).json({
184+
message: "Not Found for updating a customer with id = " + customerId,
185+
customer: "",
186+
error: "404"
187+
});
188+
} else {
189+
// update new change to database
190+
let updatedObject = {
191+
firstname: req.body.firstname,
192+
lastname: req.body.lastname,
193+
address: req.body.address,
194+
age: req.body.age
195+
}
196+
let result = await Customer.update(updatedObject, {returning: true, where: {id: customerId}});
197+
198+
// return the response to client
199+
if(!result) {
200+
res.status(500).json({
201+
message: "Error -> Can not update a customer with id = " + req.params.id,
202+
error: "Can NOT Updated",
203+
});
204+
}
205+
206+
res.status(200).json({
207+
message: "Update successfully a Customer with id = " + customerId,
208+
customer: updatedObject,
209+
});
210+
}
211+
} catch(error){
212+
res.status(500).json({
213+
message: "Error -> Can not update a customer with id = " + req.params.id,
214+
error: error.message
215+
});
216+
}
217+
}
218+
219+
exports.deleteById = async (req, res) => {
220+
try{
221+
let customerId = req.params.id;
222+
let customer = await Customer.findByPk(customerId);
223+
224+
if(!customer){
225+
res.status(404).json({
226+
message: "Does Not exist a Customer with id = " + customerId,
227+
error: "404",
228+
});
229+
} else {
230+
await customer.destroy();
231+
res.status(200).json({
232+
message: "Delete Successfully a Customer with id = " + customerId,
233+
customer: customer,
234+
});
235+
}
236+
} catch(error) {
237+
res.status(500).json({
238+
message: "Error -> Can NOT delete a customer with id = " + req.params.id,
239+
error: error.message,
240+
});
241+
}
242+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Copyright by https://loizenai.com
3+
* youtube loizenai
4+
*/
5+
6+
module.exports = (sequelize, Sequelize) => {
7+
const Customer = sequelize.define('customer', {
8+
id: {
9+
type: Sequelize.INTEGER,
10+
autoIncrement: true,
11+
primaryKey: true
12+
},
13+
firstname: {
14+
type: Sequelize.STRING
15+
},
16+
lastname: {
17+
type: Sequelize.STRING
18+
},
19+
address: {
20+
type: Sequelize.STRING
21+
},
22+
age: {
23+
type: Sequelize.INTEGER
24+
},
25+
copyrightby: {
26+
type: Sequelize.STRING,
27+
defaultValue: 'https://loizenai.com'
28+
}
29+
});
30+
31+
return Customer;
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* Copyright by https://loizenai.com
3+
* youtube loizenai
4+
*/
5+
6+
let express = require('express');
7+
let router = express.Router();
8+
9+
const customers = require('../controllers/controller.js');
10+
11+
router.post('/api/customers/create', customers.create);
12+
router.get('/api/customers/all', customers.retrieveAllCustomers);
13+
router.get('/api/customers/onebyid/:id', customers.getCustomerById);
14+
router.get('/api/customers/filteringbyage', customers.filteringByAge);
15+
router.get('/api/customers/pagination', customers.pagination);
16+
router.get('/api/customers/pagefiltersort', customers.pagingfilteringsorting);
17+
router.put('/api/customers/update/:id', customers.updateById);
18+
router.delete('/api/customers/delete/:id', customers.deleteById);
19+
20+
module.exports = router;

0 commit comments

Comments
 (0)