├── .gitignore ├── README.md ├── app ├── config │ └── db.config.js ├── controllers │ └── tutorial.controller.js ├── models │ ├── index.js │ └── tutorial.model.js └── routes │ └── turorial.routes.js ├── package.json └── server.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | package-lock.json -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Node.js Pagination & PostgreSQL example with Express 2 | 3 | For more detail, please visit: 4 | > [Node.js Express Pagination & PostgreSQL example](https://bezkoder.com/node-js-pagination-postgresql/) 5 | 6 | Front-end that works well with this Back-end: 7 | > [React Pagination with API using Material-UI](https://bezkoder.com/react-pagination-material-ui/) 8 | 9 | > [React Table Pagination with react-table 7](https://bezkoder.com/react-table-pagination-server-side/) 10 | 11 | > [Angular 8 Pagination example | ngx-pagination](https://bezkoder.com/ngx-pagination-angular-8/) 12 | 13 | > [Angular 10 Pagination example | ngx-pagination](https://bezkoder.com/angular-10-pagination-ngx/) 14 | 15 | > [Angular 11 Pagination example | ngx-pagination](https://bezkoder.com/angular-11-pagination-ngx/) 16 | 17 | > [Vue Pagination with Axios and API example](https://bezkoder.com/vue-pagination-axios/) 18 | 19 | > [Vuetify Pagination (Server side) example](https://bezkoder.com/vuetify-pagination-server-side/) 20 | 21 | More Practice: 22 | > [Node.js CRUD Rest APIs with Express, Sequelize & PostgreSQL example](https://bezkoder.com/node-express-sequelize-postgresql/) 23 | 24 | Security: 25 | > [Node.js JWT Authentication & Authorization with PostgreSQL example](https://bezkoder.com/node-js-jwt-authentication-postgresql/) 26 | 27 | Associations: 28 | > [Sequelize Associations: One-to-Many Relationship example](https://bezkoder.com/sequelize-associate-one-to-many/) 29 | 30 | > [Sequelize Associations: Many-to-Many Relationship example](https://bezkoder.com/sequelize-associate-many-to-many/) 31 | 32 | Fullstack CRUD App: 33 | > [Vue.js + Node.js + Express + PostgreSQL example](https://bezkoder.com/vue-node-express-postgresql/) 34 | 35 | > [Angular 8 + Node.js + Express + PostgreSQL example](https://bezkoder.com/angular-node-express-postgresql/) 36 | 37 | > [Angular 10 + Node.js + Express + PostgreSQL example](https://bezkoder.com/angular-10-node-express-postgresql/) 38 | 39 | > [Angular 11 + Node.js + Express + PostgreSQL example](https://bezkoder.com/angular-11-node-js-express-postgresql/) 40 | 41 | > [React + Node.js + Express + PostgreSQL example](https://bezkoder.com/react-node-express-postgresql/) 42 | 43 | Integration (run back-end & front-end on same server/port) 44 | > [Integrate React with Node.js Restful Services](https://bezkoder.com/integrate-react-express-same-server-port/) 45 | 46 | > [Integrate Angular with Node.js Restful Services](https://bezkoder.com/integrate-angular-10-node-js/) 47 | 48 | > [Integrate Vue with Node.js Restful Services](https://bezkoder.com/serve-vue-app-express/) 49 | 50 | ## Project setup 51 | ``` 52 | npm install 53 | ``` 54 | 55 | ### Run 56 | ``` 57 | node server.js 58 | ``` 59 | -------------------------------------------------------------------------------- /app/config/db.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | HOST: "localhost", 3 | USER: "postgres", 4 | PASSWORD: "123", 5 | DB: "testdb", 6 | dialect: "postgres", 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /app/controllers/tutorial.controller.js: -------------------------------------------------------------------------------- 1 | const db = require("../models"); 2 | const Tutorial = db.tutorials; 3 | const Op = db.Sequelize.Op; 4 | 5 | const getPagination = (page, size) => { 6 | const limit = size ? +size : 3; 7 | const offset = page ? page * limit : 0; 8 | 9 | return { limit, offset }; 10 | }; 11 | 12 | const getPagingData = (data, page, limit) => { 13 | const { count: totalItems, rows: tutorials } = data; 14 | const currentPage = page ? +page : 0; 15 | const totalPages = Math.ceil(totalItems / limit); 16 | 17 | return { totalItems, tutorials, totalPages, currentPage }; 18 | }; 19 | 20 | // Create and Save a new Tutorial 21 | exports.create = (req, res) => { 22 | // Validate request 23 | if (!req.body.title) { 24 | res.status(400).send({ 25 | message: "Content can not be empty!" 26 | }); 27 | return; 28 | } 29 | 30 | // Create a Tutorial 31 | const tutorial = { 32 | title: req.body.title, 33 | description: req.body.description, 34 | published: req.body.published ? req.body.published : false 35 | }; 36 | 37 | // Save Tutorial in the database 38 | Tutorial.create(tutorial) 39 | .then(data => { 40 | res.send(data); 41 | }) 42 | .catch(err => { 43 | res.status(500).send({ 44 | message: 45 | err.message || "Some error occurred while creating the Tutorial." 46 | }); 47 | }); 48 | }; 49 | 50 | // Retrieve all Tutorials from the database. 51 | exports.findAll = (req, res) => { 52 | const { page, size, title } = req.query; 53 | var condition = title ? { title: { [Op.like]: `%${title}%` } } : null; 54 | 55 | const { limit, offset } = getPagination(page, size); 56 | 57 | Tutorial.findAndCountAll({ where: condition, limit, offset }) 58 | .then(data => { 59 | const response = getPagingData(data, page, limit); 60 | res.send(response); 61 | }) 62 | .catch(err => { 63 | res.status(500).send({ 64 | message: 65 | err.message || "Some error occurred while retrieving tutorials." 66 | }); 67 | }); 68 | }; 69 | 70 | // Find a single Tutorial with an id 71 | exports.findOne = (req, res) => { 72 | const id = req.params.id; 73 | 74 | Tutorial.findByPk(id) 75 | .then(data => { 76 | res.send(data); 77 | }) 78 | .catch(err => { 79 | res.status(500).send({ 80 | message: "Error retrieving Tutorial with id=" + id 81 | }); 82 | }); 83 | }; 84 | 85 | // Update a Tutorial by the id in the request 86 | exports.update = (req, res) => { 87 | const id = req.params.id; 88 | 89 | Tutorial.update(req.body, { 90 | where: { id: id } 91 | }) 92 | .then(num => { 93 | if (num == 1) { 94 | res.send({ 95 | message: "Tutorial was updated successfully." 96 | }); 97 | } else { 98 | res.send({ 99 | message: `Cannot update Tutorial with id=${id}. Maybe Tutorial was not found or req.body is empty!` 100 | }); 101 | } 102 | }) 103 | .catch(err => { 104 | res.status(500).send({ 105 | message: "Error updating Tutorial with id=" + id 106 | }); 107 | }); 108 | }; 109 | 110 | // Delete a Tutorial with the specified id in the request 111 | exports.delete = (req, res) => { 112 | const id = req.params.id; 113 | 114 | Tutorial.destroy({ 115 | where: { id: id } 116 | }) 117 | .then(num => { 118 | if (num == 1) { 119 | res.send({ 120 | message: "Tutorial was deleted successfully!" 121 | }); 122 | } else { 123 | res.send({ 124 | message: `Cannot delete Tutorial with id=${id}. Maybe Tutorial was not found!` 125 | }); 126 | } 127 | }) 128 | .catch(err => { 129 | res.status(500).send({ 130 | message: "Could not delete Tutorial with id=" + id 131 | }); 132 | }); 133 | }; 134 | 135 | // Delete all Tutorials from the database. 136 | exports.deleteAll = (req, res) => { 137 | Tutorial.destroy({ 138 | where: {}, 139 | truncate: false 140 | }) 141 | .then(nums => { 142 | res.send({ message: `${nums} Tutorials were deleted successfully!` }); 143 | }) 144 | .catch(err => { 145 | res.status(500).send({ 146 | message: 147 | err.message || "Some error occurred while removing all tutorials." 148 | }); 149 | }); 150 | }; 151 | 152 | // find all published Tutorial 153 | exports.findAllPublished = (req, res) => { 154 | const { page, size } = req.query; 155 | const { limit, offset } = getPagination(page, size); 156 | 157 | Tutorial.findAndCountAll({ where: { published: true }, limit, offset }) 158 | .then(data => { 159 | const response = getPagingData(data, page, limit); 160 | res.send(response); 161 | }) 162 | .catch(err => { 163 | res.status(500).send({ 164 | message: 165 | err.message || "Some error occurred while retrieving tutorials." 166 | }); 167 | }); 168 | }; 169 | -------------------------------------------------------------------------------- /app/models/index.js: -------------------------------------------------------------------------------- 1 | const dbConfig = require("../config/db.config.js"); 2 | 3 | const Sequelize = require("sequelize"); 4 | const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, { 5 | host: dbConfig.HOST, 6 | dialect: dbConfig.dialect, 7 | 8 | pool: { 9 | max: dbConfig.pool.max, 10 | min: dbConfig.pool.min, 11 | acquire: dbConfig.pool.acquire, 12 | idle: dbConfig.pool.idle 13 | } 14 | }); 15 | 16 | const db = {}; 17 | 18 | db.Sequelize = Sequelize; 19 | db.sequelize = sequelize; 20 | 21 | db.tutorials = require("./tutorial.model.js")(sequelize, Sequelize); 22 | 23 | module.exports = db; 24 | -------------------------------------------------------------------------------- /app/models/tutorial.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Tutorial = sequelize.define("tutorial", { 3 | title: { 4 | type: Sequelize.STRING 5 | }, 6 | description: { 7 | type: Sequelize.STRING 8 | }, 9 | published: { 10 | type: Sequelize.BOOLEAN 11 | } 12 | }); 13 | 14 | return Tutorial; 15 | }; 16 | -------------------------------------------------------------------------------- /app/routes/turorial.routes.js: -------------------------------------------------------------------------------- 1 | module.exports = app => { 2 | const tutorials = require("../controllers/tutorial.controller.js"); 3 | 4 | var router = require("express").Router(); 5 | 6 | // Create a new Tutorial 7 | router.post("/", tutorials.create); 8 | 9 | // Retrieve all Tutorials 10 | router.get("/", tutorials.findAll); 11 | 12 | // Retrieve all published Tutorials 13 | router.get("/published", tutorials.findAllPublished); 14 | 15 | // Retrieve a single Tutorial with id 16 | router.get("/:id", tutorials.findOne); 17 | 18 | // Update a Tutorial with id 19 | router.put("/:id", tutorials.update); 20 | 21 | // Delete a Tutorial with id 22 | router.delete("/:id", tutorials.delete); 23 | 24 | // Create a new Tutorial 25 | router.delete("/", tutorials.deleteAll); 26 | 27 | app.use("/api/tutorials", router); 28 | }; 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-express-pagination-postgresql", 3 | "version": "1.0.0", 4 | "description": "Node.js Rest Apis with Express, Sequelize & M", 5 | "main": "server.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "nodejs", 11 | "express", 12 | "sequelize", 13 | "rest", 14 | "api", 15 | "postgresql" 16 | ], 17 | "author": "bezkoder", 18 | "license": "ISC", 19 | "dependencies": { 20 | "body-parser": "^1.19.0", 21 | "cors": "^2.8.5", 22 | "express": "^4.17.1", 23 | "pg": "^7.17.1", 24 | "pg-hstore": "^2.3.3", 25 | "sequelize": "^5.21.3" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const bodyParser = require("body-parser"); 3 | const cors = require("cors"); 4 | 5 | const app = express(); 6 | 7 | var corsOptions = { 8 | origin: "http://localhost:8081" 9 | }; 10 | 11 | app.use(cors(corsOptions)); 12 | 13 | // parse requests of content-type - application/json 14 | app.use(bodyParser.json()); 15 | 16 | // parse requests of content-type - application/x-www-form-urlencoded 17 | app.use(bodyParser.urlencoded({ extended: true })); 18 | 19 | const db = require("./app/models"); 20 | db.sequelize.sync(); 21 | // // drop the table if it already exists 22 | // db.sequelize.sync({ force: true }).then(() => { 23 | // console.log("Drop and re-sync db."); 24 | // }); 25 | 26 | // simple route 27 | app.get("/", (req, res) => { 28 | res.json({ message: "Welcome to bezkoder application." }); 29 | }); 30 | 31 | require("./app/routes/turorial.routes")(app); 32 | 33 | // set port, listen for requests 34 | const PORT = process.env.PORT || 8080; 35 | app.listen(PORT, () => { 36 | console.log(`Server is running on port ${PORT}.`); 37 | }); 38 | --------------------------------------------------------------------------------