Simpul js mysql rest-api github

Buat file dengan nama dan lokasi berikut .env dan salin konten dari .env.example ke dalamnya. Ganti nilainya dengan konfigurasi spesifik Anda. Jangan khawatir, file ini ada di .gitignore sehingga tidak akan didorong ke github

Komit ini bukan milik cabang mana pun di repositori ini, dan mungkin milik garpu di luar repositori

Anda tidak dapat melakukan tindakan tersebut saat ini

Anda masuk dengan tab atau jendela lain. Muat ulang untuk menyegarkan sesi Anda. Anda keluar di tab atau jendela lain. Muat ulang untuk menyegarkan sesi Anda

Kami akan mulai membangun Node. js Rest API dengan Express, Sequelize, dan MySQL. Di sini kita akan menggunakan Sequelize untuk berinteraksi dengan instance MySQL

Aplikasi yang dibutuhkan

  • Docker adalah sekumpulan platform sebagai produk layanan yang menggunakan virtualisasi tingkat OS untuk mengirimkan perangkat lunak dalam paket yang disebut wadah. Kontainer diisolasi satu sama lain dan menggabungkan perangkat lunak, pustaka, dan file konfigurasinya sendiri;
  • Node. js adalah platform yang dibangun di atas runtime JavaScript Chrome untuk membangun aplikasi jaringan yang cepat dan skalabel dengan mudah. Node. js adalah lingkungan runtime lintas platform sumber terbuka untuk mengembangkan aplikasi sisi server dan jaringan
  • ExpressJS adalah salah satu kerangka kerja web paling populer untuk node.js. js. Itu dibangun di atas node. js modul HTTP dan menambahkan dukungan untuk perutean, middleware, sistem tampilan, dll. Ini sangat sederhana dan minimal, tidak seperti kerangka kerja lain yang mencoba melakukan terlalu banyak, sehingga mengurangi fleksibilitas bagi pengembang untuk memiliki pilihan desain sendiri.
  • Sequelize adalah Node berbasis janji. js ORM untuk Postgres, MySQL, MariaDB, SQLite, dan Microsoft SQL Server. Ini fitur dukungan transaksi yang solid, hubungan, pemuatan bersemangat dan malas, replikasi baca dan banyak lagi
  • CORS adalah sebuah simpul. js untuk menyediakan middleware Connect/Express yang dapat digunakan untuk mengaktifkan CORS dengan berbagai opsi
  • body-parser Mengurai badan permintaan masuk di middleware sebelum penangan Anda, tersedia di bawah properti
    const express = require("express");
    const bodyParser = require("body-parser");
    const cors = require("cors");
    const server = express();
    const db = require("./models");
    const corsSettings = {
      originL: "http://localhost:8081"
    };
    
    const api = require("./routes/index");
    server.use(cors(corsSettings));
    
    // Parse request of content-type - application/json
    server.use(bodyParser.json());
    
    // parse requests of content-type -application/x-www-form-urlencoded
    server.use(bodyParser.urlencoded({ extended: true }));
    
    create a simple route
    server.get("/", (\_req, res) => {
       res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
    });
    
    // set listening ports for request
    const port = process.env.PORT || 8080;
    
    server.listen(port, () => {
      console.log("Server running on port : " + port );
    });
    2
  • Tukang pos adalah alat pengembangan API (antarmuka pemrograman aplikasi) yang membantu membangun, menguji, dan memodifikasi API. Ini memiliki kemampuan untuk membuat berbagai jenis permintaan HTTP (GET, POST, PUT, PATCH, dll. )

Node. Ikhtisar API Istirahat CRUD js

Kami akan membangun Rest Apis yang dapat membuat, mengambil, memperbarui, menghapus, dan menemukan Postingan berdasarkan judul

Pertama, kita mulai dengan server web Express. Selanjutnya, kita tambahkan konfigurasi untuk database MySQL, buat

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};

const api = require("./routes/index");
server.use(cors(corsSettings));

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});
3 model dengan Sequelize, tulis controller. Kemudian kami menentukan rute untuk menangani semua operasi CRUD (termasuk pencari khusus)

Tabel berikut menampilkan ikhtisar Rest API yang akan diekspor

MethodsUrlsActionsGETapi/posts/allGet all PostsGETapi/posts/. idGet post by
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};

const api = require("./routes/index");
server.use(cors(corsSettings));

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});
4POSTapi/posts/createCreate new postPUTapi/posts/update/. idPerbarui posting oleh
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};

const api = require("./routes/index");
server.use(cors(corsSettings));

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});
4DELETEapi/posts/hapus/. idHapus postingan oleh
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};

const api = require("./routes/index");
server.use(cors(corsSettings));

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});
4DELETEapi/posts/deleteallHapus semua postinganGETapi/posts/publishedDapatkan semua postingan yang dipublikasikanGETapi/posts?title=’test’Dapatkan semua postingan yang judulnya berisi
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};

const api = require("./routes/index");
server.use(cors(corsSettings));

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});
7GETapi/posts/publisher?name=’christos’Dapatkan Semua postingan dengan nama penerbit
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};

const api = require("./routes/index");
server.use(cors(corsSettings));

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});
8

Ini adalah struktur proyek kami

Sekarang mari kita mulai Membuat Node. Aplikasi js

Pertama kita buat foldernya

$ mkdir node_rest_api_with_mysql $ cd node_rest_api_with_mysql

Selanjutnya, kita menginisialisasi Node. Aplikasi js dengan sebuah paket. file json

npm init

name: (nodejs-express-sequelize-mysql) 
version: (1.0.0) 
description: Node.js Rest Apis with Express, Sequelize & MySQL.
entry point: (index.js) server.js
test command: 
git repository: 
keywords: nodejs, express, sequelize, mysql, rest, api, docker
author: Christos Ploutarchou
license: (ISC)

Is this ok? (yes) yes

Jika Anda sudah menginstal MySQL di PC Anda, Anda dapat mengabaikan Langkah-langkah berikut

Selanjutnya, perlu menginstal buruh pelabuhan untuk mysql dan phpMyAdmin

  1. Instal Docker (Pelajari lebih lanjut tentang instalasi docker di sini)
  2. Masuk ke direktori root proyek
  3. Atas komposisi

docker-compose up -d

  • Akses phpmyadmin

your_ip. 8183 Server. nama pengguna mysql. kata sandi akar/akar. root/pass

  • Akses mysql di terminal

docker exec -itu mysql_container_name mysql -u root -p

Docker phpmyadmin ENV

PMA_ARBITRARY

ketika diatur ke 1 koneksi ke server sewenang-wenang akan diizinkan

PPMA_HOST

tentukan alamat / nama host dari server MySQL

PMA_PORT

menentukan port dari server MySQL

  • Jika Anda memerlukan informasi lebih lanjut tentang gambar phpmyadmin. BACA DI SINI
  • Jika Anda memerlukan informasi lebih lanjut tentang gambar mysql. BACA DI SINI

Kami juga perlu menginstal modul yang diperlukan.

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};

const api = require("./routes/index");
server.use(cors(corsSettings));

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});
9,
module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "pass",
  DB: "restapi",
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 50000
  }
};
0,
module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "pass",
  DB: "restapi",
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 50000
  }
};
1 dan
module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "pass",
  DB: "restapi",
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 50000
  }
};
2 di proyek kami

Jalankan perintah

npm install express body-parser cors sekuel mysql2 --save

Saat instalasi selesai paket. file json akan terlihat seperti ini

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}

Siapkan server web Ekspres

Di direktori root kami perlu membuat server baru. file js

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};

const api = require("./routes/index");
server.use(cors(corsSettings));

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});

Apa yang kita lakukan di sini
– impor

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};

const api = require("./routes/index");
server.use(cors(corsSettings));

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});
_9,
module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "pass",
  DB: "restapi",
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 50000
  }
};
2 dan
module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "pass",
  DB: "restapi",
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 50000
  }
};
5 modul

  • Express adalah untuk membangun Rest apis
  • body-parser membantu mengurai permintaan dan membuat objek
    const express = require("express");
    const bodyParser = require("body-parser");
    const cors = require("cors");
    const server = express();
    const db = require("./models");
    const corsSettings = {
      originL: "http://localhost:8081"
    };
    
    const api = require("./routes/index");
    server.use(cors(corsSettings));
    
    // Parse request of content-type - application/json
    server.use(bodyParser.json());
    
    // parse requests of content-type -application/x-www-form-urlencoded
    server.use(bodyParser.urlencoded({ extended: true }));
    
    create a simple route
    server.get("/", (\_req, res) => {
       res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
    });
    
    // set listening ports for request
    const port = process.env.PORT || 8080;
    
    server.listen(port, () => {
      console.log("Server running on port : " + port );
    });
    2
  • cors menyediakan middleware Express untuk mengaktifkan CORS dengan berbagai opsi

– buat aplikasi Express, lalu tambahkan

module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "pass",
  DB: "restapi",
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 50000
  }
};
_2 dan
module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "pass",
  DB: "restapi",
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 50000
  }
};
5 middleware menggunakan metode
module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "pass",
  DB: "restapi",
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 50000
  }
};
9. Perhatikan bahwa kita menetapkan asal.
const dbConfig = require("../config/db.config");
const Sequelize = require("sequelize");
const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});

const db = {};
db.Sequelize = Sequelize;
db.databaseConf = database;
// function to drop existing tables and re-sync database
db.dropRestApiTable = () => {
  db.databaseConf.sync({ force: true }).then(() => {
    console.log("restTutorial table just dropped and db re-synced.");
  });
};
db.posts = require("./Sequelize.model")(database, Sequelize);
module.exports = db;
0
– menentukan rute GET yang sederhana untuk pengujian
– dengarkan pada port 8080 untuk permintaan masuk

Sekarang mari kita jalankan aplikasinya dengan menjalankan perintah berikut.

const dbConfig = require("../config/db.config");
const Sequelize = require("sequelize");
const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});

const db = {};
db.Sequelize = Sequelize;
db.databaseConf = database;
// function to drop existing tables and re-sync database
db.dropRestApiTable = () => {
  db.databaseConf.sync({ force: true }).then(() => {
    console.log("restTutorial table just dropped and db re-synced.");
  });
};
db.posts = require("./Sequelize.model")(database, Sequelize);
module.exports = db;
1
Buka browser Anda dengan URL http. // localhost. 8080/, Anda akan melihat

Ya Benar, langkah pertama selesai. Kami akan bekerja dengan Sequelize di bagian selanjutnya

Konfigurasi database MySQL & Sequelize

Di folder root, kami membuat folder config terpisah untuk konfigurasi dengan db. config. file js seperti ini

Catatan. Jika Anda tidak menulis proyek buruh pelabuhan, Maka perlu memperbarui info basis data dengan kredensial dan info lingkungan lokal Anda

module.exports = {
  HOST: "localhost",
  USER: "root",
  PASSWORD: "pass",
  DB: "restapi",
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 50000
  }
};
_

Lima parameter pertama adalah untuk koneksi MySQL

const dbConfig = require("../config/db.config");
const Sequelize = require("sequelize");
const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});

const db = {};
db.Sequelize = Sequelize;
db.databaseConf = database;
// function to drop existing tables and re-sync database
db.dropRestApiTable = () => {
  db.databaseConf.sync({ force: true }).then(() => {
    console.log("restTutorial table just dropped and db re-synced.");
  });
};
db.posts = require("./Sequelize.model")(database, Sequelize);
module.exports = db;
2 bersifat opsional, ini akan digunakan untuk konfigurasi kumpulan koneksi Sequelize

  • const dbConfig = require("../config/db.config");
    const Sequelize = require("sequelize");
    const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
      host: dbConfig.HOST,
      dialect: dbConfig.dialect,
      operatorsAliases: false,
      pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
      }
    });
    
    const db = {};
    db.Sequelize = Sequelize;
    db.databaseConf = database;
    // function to drop existing tables and re-sync database
    db.dropRestApiTable = () => {
      db.databaseConf.sync({ force: true }).then(() => {
        console.log("restTutorial table just dropped and db re-synced.");
      });
    };
    db.posts = require("./Sequelize.model")(database, Sequelize);
    module.exports = db;
    3. jumlah maksimum koneksi dalam kumpulan
  • const dbConfig = require("../config/db.config");
    const Sequelize = require("sequelize");
    const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
      host: dbConfig.HOST,
      dialect: dbConfig.dialect,
      operatorsAliases: false,
      pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
      }
    });
    
    const db = {};
    db.Sequelize = Sequelize;
    db.databaseConf = database;
    // function to drop existing tables and re-sync database
    db.dropRestApiTable = () => {
      db.databaseConf.sync({ force: true }).then(() => {
        console.log("restTutorial table just dropped and db re-synced.");
      });
    };
    db.posts = require("./Sequelize.model")(database, Sequelize);
    module.exports = db;
    4. jumlah minimum koneksi di kolam renang
  • const dbConfig = require("../config/db.config");
    const Sequelize = require("sequelize");
    const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
      host: dbConfig.HOST,
      dialect: dbConfig.dialect,
      operatorsAliases: false,
      pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
      }
    });
    
    const db = {};
    db.Sequelize = Sequelize;
    db.databaseConf = database;
    // function to drop existing tables and re-sync database
    db.dropRestApiTable = () => {
      db.databaseConf.sync({ force: true }).then(() => {
        console.log("restTutorial table just dropped and db re-synced.");
      });
    };
    db.posts = require("./Sequelize.model")(database, Sequelize);
    module.exports = db;
    5. waktu maksimum, dalam milidetik, koneksi dapat menganggur sebelum dirilis
  • const dbConfig = require("../config/db.config");
    const Sequelize = require("sequelize");
    const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
      host: dbConfig.HOST,
      dialect: dbConfig.dialect,
      operatorsAliases: false,
      pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
      }
    });
    
    const db = {};
    db.Sequelize = Sequelize;
    db.databaseConf = database;
    // function to drop existing tables and re-sync database
    db.dropRestApiTable = () => {
      db.databaseConf.sync({ force: true }).then(() => {
        console.log("restTutorial table just dropped and db re-synced.");
      });
    };
    db.posts = require("./Sequelize.model")(database, Sequelize);
    module.exports = db;
    6. waktu maksimum, dalam milidetik, kumpulan itu akan mencoba mendapatkan koneksi sebelum melempar kesalahan

Untuk informasi lebih lanjut, Anda dapat mengunjungi

Inisialisasi Sekuel

Kita akan menginisialisasi Sequelize di folder app/models yang akan berisi model pada langkah berikutnya

Sekarang buat app/models/index. js dengan kode berikut

const dbConfig = require("../config/db.config");
const Sequelize = require("sequelize");
const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});

const db = {};
db.Sequelize = Sequelize;
db.databaseConf = database;
// function to drop existing tables and re-sync database
db.dropRestApiTable = () => {
  db.databaseConf.sync({ force: true }).then(() => {
    console.log("restTutorial table just dropped and db re-synced.");
  });
};
db.posts = require("./Sequelize.model")(database, Sequelize);
module.exports = db;

Jangan lupa untuk memanggil metode

const dbConfig = require("../config/db.config");
const Sequelize = require("sequelize");
const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});

const db = {};
db.Sequelize = Sequelize;
db.databaseConf = database;
// function to drop existing tables and re-sync database
db.dropRestApiTable = () => {
  db.databaseConf.sync({ force: true }).then(() => {
    console.log("restTutorial table just dropped and db re-synced.");
  });
};
db.posts = require("./Sequelize.model")(database, Sequelize);
module.exports = db;
_7 di server. js

const db = require("./models");
db.databaseConf.sync();

Setelah itu server Anda. js harus terlihat seperti di bawah ini

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const server = express();
const db = require("./models");
const corsSettings = {
  originL: "http://localhost:8081"
};
server.use(cors(corsSettings));

const db = require("./models");

// Parse request of content-type - application/json
server.use(bodyParser.json());

// parse requests of content-type -application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: true }));

create a simple route
server.get("/", (\_req, res) => {
   res.json({ message: "Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou" });
});

// set listening ports for request
const port = process.env.PORT || 8080;

server.listen(port, () => {
  console.log("Server running on port : " + port );
});
db.databaseConf.sync();

Tentukan Model Sekuelisasi

Di folder model, buat Sequelize. model. file js seperti ini

module.exports = (database, Sequelize) => {
  return database.define("restTutorial", {
    title: {
      type: Sequelize.STRING
    },
    description: {
      type: Sequelize.TEXT
    },
    published: {
      type: Sequelize.BOOLEAN
    },
    publisher: {
      type: Sequelize.STRING
    }
  });
};

Model Sequelize ini merepresentasikan tabel posts pada database MySQL. Kolom ini akan dibuat secara otomatis. id, judul, deskripsi, diterbitkan, penerbit, dibuat, diperbarui

Setelah menginisialisasi Sequelize, kita tidak perlu menulis fungsi CRUD, Sequelize mendukung semuanya

  • Buat postingan baru.
    const dbConfig = require("../config/db.config");
    const Sequelize = require("sequelize");
    const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
      host: dbConfig.HOST,
      dialect: dbConfig.dialect,
      operatorsAliases: false,
      pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
      }
    });
    
    const db = {};
    db.Sequelize = Sequelize;
    db.databaseConf = database;
    // function to drop existing tables and re-sync database
    db.dropRestApiTable = () => {
      db.databaseConf.sync({ force: true }).then(() => {
        console.log("restTutorial table just dropped and db re-synced.");
      });
    };
    db.posts = require("./Sequelize.model")(database, Sequelize);
    module.exports = db;
    8
  • Dapatkan semua posting.
    const dbConfig = require("../config/db.config");
    const Sequelize = require("sequelize");
    const database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
      host: dbConfig.HOST,
      dialect: dbConfig.dialect,
      operatorsAliases: false,
      pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
      }
    });
    
    const db = {};
    db.Sequelize = Sequelize;
    db.databaseConf = database;
    // function to drop existing tables and re-sync database
    db.dropRestApiTable = () => {
      db.databaseConf.sync({ force: true }).then(() => {
        console.log("restTutorial table just dropped and db re-synced.");
      });
    };
    db.posts = require("./Sequelize.model")(database, Sequelize);
    module.exports = db;
    _9
  • Perbarui posting dengan id.
    const db = require("./models");
    db.databaseConf.sync();
    0
  • Hapus postingan.
    const db = require("./models");
    db.databaseConf.sync();
    1
  • Hapus semua postingan.
    const db = require("./models");
    db.databaseConf.sync();
    2
  • Dapatkan semua posting dengan judul.
    const db = require("./models");
    db.databaseConf.sync();
    3
  • Dapatkan semua posting dengan nama penerbit.
    const db = require("./models");
    db.databaseConf.sync();
    4

Fungsi-fungsi ini akan digunakan pada Pengontrol kami

Buat Pengontrol

Di dalam folder app/controllers, mari buat Posting. js dengan fungsi CRUD ini

  • membuat
  • Temukan semua
  • findOne
  • memperbarui
  • menghapus
  • Hapus semua
  • findAllPublished
  • findByPublisherName

const db = require('../models')
const postObj = db.posts
const Op = db.Sequelize.Op

// Create and save new Post
exports.create = (request, result) => {
}

// Save Post object to db
postObj.create(post).then(data => {

}

// Retrieve all Post (Receive data with condition).
exports.getAllPosts = (request, result) => {

}

// Get Post object by ID
exports.getPostByID = (request, result) => {

}
// Update a Post object by the id
exports.updatePostByID = (request, result) => {

}

// Delete Post object by ID
exports.deletePostByID = (request, result) => {

}

// Delete All Posts objects from database
exports.deleteAllPosts = (request, result) => {

}

// Get all published Post
exports.getAllPublishedPosts = (request, result) => {

}

// Get all published Post by Publisher Name
exports.getAllPostsByPublisherName = (request, result) => {

}

// Get all published post by Title
exports.getPostByTitle = (request, result) => {

}

Sekarang mari kita implementasikan fungsi-fungsi ini

Buat objek posting baru

// Create and save new Post
exports.create = (request, result) => {
  if (!request.body.title) {
    result.status(400).send({
      message: "Content cannot be empty"
    });
  }

  // Create a Post object
  const post = {
    title: request.body.title,
    description: request.body.description,
    published: request.body.published ? request.body.published : false,
    publisher: request.body.publisher ? request.body.publisher : false
  };

  // Save Post object to db
  postObj.create(post).then(data => {
    result.send(data);
  }).catch(err => {
    result.status(500).send({
      message: err.message || "Some error occurred while saving."
    });
  });
};

Dapatkan semua objek (Dengan judul posting)

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
0

Pada fungsi itu kami menggunakan

const db = require("./models");
db.databaseConf.sync();
_5 untuk mendapatkan string kueri dari Permintaan dan menganggapnya sebagai syarat untuk metode
const db = require("./models");
db.databaseConf.sync();
6

Dapatkan objek posting tunggal (Dengan ID pos)

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
1

Perbarui objek Posting dengan id

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
2

Hapus objek Posting dengan ID

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
3

Hapus Semua objek Posting dari database

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
4

Dapatkan semua objek Posting yang diterbitkan dari database

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
5

Dapatkan semua objek Posting yang diterbitkan dari database

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
6

Tentukan Rute

Saat klien mengirim permintaan untuk titik akhir menggunakan permintaan HTTP (GET, POST, PUT, DELETE), kita perlu menentukan bagaimana server akan merespons dengan menyiapkan rute

Sekarang mari kita membuat indeks. js di dalam folder route/ dengan konten seperti ini

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
7

Anda dapat melihat bahwa kami menggunakan pengontrol dari

const db = require("./models");
db.databaseConf.sync();
7

Kami juga perlu memasukkan rute di server. js (tepat sebelum

const db = require("./models");
db.databaseConf.sync();
_8)

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
8

Setelah itu perbarui server kami. file js harus terlihat seperti

{
  "name": "node_rest_api_with_mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Api with Express, Sequelize, MySQL & phpMyAdmin .",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cploutarchou/node_rest_api_with_mysql.git"
  },
  "keywords": [
    "node",
    "rest-api",
    "tutorial",
    "mysql",
    "phpMyAdmin",
    "docker",
    "node.js",
    "sequilize"
  ],
  "author": "Christos Ploutarchou",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cploutarchou/node_rest_api_with_mysql/issues"
  },
  "homepage": "https://github.com/cploutarchou/node_rest_api_with_mysql#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "nodemon": "^2.0.2"
  }
}
_9

Catatan. Dalam pengembangan, Anda mungkin perlu menghapus tabel yang ada dan menyinkronkan ulang database. Jadi mari kita buat fungsi baru pada models/index. js untuk menerapkan itu