MySQL Sequelize & Express-Phần 2 : Building REST CRUD API

Các bạn xem phần 1:
http://www.gacoder.info/mysql-sequelize-express-phan-1-cai-dat-va-tao-table/

Để không hiển thị log Sequelize trong command các bạn thêm vào file index.js

logging: false

File index.js

const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
    host: dbConfig.HOST,
    dialect: dbConfig.dialect,
    operatorsAliases: 0,
    logging: false,
    pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
    }
});

Chúng ta sẽ đi xây dựng Rest api như sau:

Methods URL Action
GET api/news get all news
GET api/news/:id get New by id
POST api/news add new New
PUT api/news/:id update New by id
DELETE api/news/:id remove New by id
DELETE api/news remove all news
GET api/news/published find all published news
GET api/news?title=[kw] find all news which title contains ‘kw’

Tạo folder controllers và tạo file controllers/new.controller.js với các function curd như sau:

Create New create(object)
Find New by id findByPk(id)
get all News findAll()
update a New by id update(data, where: { id: id })
remove a New destroy(where: { id: id })
remove all News destroy(where: {})
find all News by title findAll({ where: { title: … } })

Create New:

Retrieving Objects

Retrieving a Single Object

Updating An Object

Deleting An Object

Deleting All Objects

Finding all Objects by Condition

File new.controller.js hoàn chỉnh

Tạo route:
/api/news: GET, POST, DELETE
/api/news/:id: GET, PUT, DELETE
/api/news/published: GET

Tạo folder routes và tao file new.routes.js

Import route vào file server.js

require("./routes/new.routes.js")(app);

File server.js hoàn chỉnh:

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(cors());
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
const db = require("./models");
db.sequelize.sync();
// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to gacoder.info" });
});
// set port, listen for requests
require("./routes/new.routes.js")(app);

const PORT = process.env.PORT || 8081;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

Testing the API with Postman
Tạo 1 new mới:
Link:localhost:8081/api/news
Method:Post

Retrieving All News Using GET

Link:localhost:8081/api/news
Method:get

Retrieving A Single New Using GET/news/:id API
Link:localhost:8081/api/news/1
Method:get

Update a new using PUT /news/:id API

Link:localhost:8081/api/news/1
Method:put

Finding All News where Title=”Covid” Using GET/news?title=Covid API

Link:localhost:8081/api/news?title=Covid
Method:get

Finding All Published News Using GET/news/published API

Link:localhost:8081/api/news/published
Method:Get

Deleting A New Using DELETE/news/:id API
Link:localhost:8081/api/news/2
Method:Delete

Deleting all News using DELETE /news API

Link:localhost:8081/api/news
Method:Delete

Link code demo here