Connecting MySQL to your node sequilize application
Goal
To successfully connect our node application to mysql using sequilize adapter.
Prerequisites
To follow this artice along with me effectively:
You will need to have Node.js installed on your computer.
A basic understanding of Node.js.
A suitable code editor. I will go with Visual Studio Code.
Packages
npm i -s dot-env sequelize express cors
Start by defining our database credentials in my .env and install .env
.env
DB_HOST="localhost"
DB_USER="root"
DB_PW="root"
DB_NAME="youtube"
We access the values in the .env file by firstly requiring dotenv in our db config file like so.
config.js
require("dotenv").config({ path: ".env" });
module.exports = {
HOST: process.env.DB_HOST,
USER: process.env.DB_USER,
PASSWORD: process.env.DB_PW,
DB: process.env.DB_NAME,
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
},
};
Models
module.exports = (sequelize, Sequelize) => {
const Channel = sequelize.define("channel", {
id: {
type: Sequelize.STRING,
primaryKey: true,
},
channel_name: {
type: Sequelize.STRING,
},
});
return Channel;
};
Controllers
const db = require("../models");
const Channel = db.channels;
const Op = db.Sequelize.Op;
// Create and Save a new Channel
exports.create = (req, res) => {
// Validate request
if (!req.body.channel_name) {
res.status(400).send({
message: "Content can not be empty!",
});
return;
}
// Create a Channel
const channel = {
channel_name: req.body.channel_name,
};
// Save Channel in the database
Channel.create(channel)
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Channel.",
});
});
};
Routers
module.exports = (app) => {
const channels = require("../controllers/channel.controller.js");
var router = require("express").Router();
// Create a new Tutorial
router.post("/", channels.create);
// Delete all channels
router.delete("/", channels.deleteAll);
app.use("/api/channels", router);
};
Main Server
const express = require("express");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081",
};
app.use(morgan("tiny"));
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
const db = require("./app/models");
db.sequelize
.sync()
.then(() => {
console.log("Synced db.");
})
.catch((err) => {
console.log("Failed to sync db: " + err.message);
});
require("./app/routes/channel.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
module.exports = app;
we run the application by
node server.js
Good day! Very interesting