BASIC ORM SEQUELIZE | Membuat REST API node js express sequelize
Sequelize is a powerful ORM (Object-Relational Mapping) for Node.js that allows you to interact with a database using JavaScript. In this article, we will explore how to create a basic REST API using Node.js, Express, and Sequelize.
Setting up the project
First, you need to create a new Node.js project and install the necessary dependencies. You can do this by running the following commands in your terminal:
mkdir sequelize-rest-api
cd sequelize-rest-api
npm init -y
npm install express sequelize mysql2
Next, you will need to create a new file called index.js
where you will write your Node.js code. Inside this file, you can start by requiring the necessary modules and setting up the Express app.
const express = require('express');
const { Sequelize, DataTypes } = require('sequelize');
const app = express();
const port = 3000;
app.use(express.json());
Connecting to the database
After setting up the Express app, you will need to create a new Sequelize instance and connect it to your database. You can do this by providing the database credentials and options to the Sequelize
constructor.
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'
});
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
Defining models
With the database connection established, you can now define your database models using Sequelize’s DataTypes
and define
methods. These models will represent the tables in your database and define their columns and data types.
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING
}
});
Creating a REST API
Finally, you can create the routes for your REST API using Express. You will need to define routes for creating, reading, updating, and deleting resources, and use Sequelize’s ORM methods to interact with the database.
app.post('/users', async (req, res) => {
const { name, email } = req.body;
const user = await User.create({ name, email });
res.json(user);
});
app.get('/users', async (req, res) => {
const users = await User.findAll();
res.json(users);
});
app.get('/users/:id', async (req, res) => {
const { id } = req.params;
const user = await User.findByPk(id);
res.json(user);
});
app.put('/users/:id', async (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
await User.update({ name, email }, { where: { id } });
res.json({ message: 'User updated successfully' });
});
app.delete('/users/:id', async (req, res) => {
const { id } = req.params;
await User.destroy({ where: { id } });
res.json({ message: 'User deleted successfully' });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
And that’s it! You have now created a basic REST API using Node.js, Express, and Sequelize. You can test the API using tools like Postman or curl, and expand it with more features and models as needed.