tech

Table of Content

Install

npm install express mysql2 sequelize bcrypt
npm install --save-dev sequelize-cli nodemon

Config DB

config/db.js

const { Sequelize } = require('sequelize');
 
const sequelize = new Sequelize('latihan', 'root', '', {
  host: 'localhost',
  dialect: 'mysql',
  logging: true,
});
 
sequelize.authenticate()
  .then(() => console.log('Terhubung ke database MySQL.'))
  .catch(err => console.error('Gagal terhubung ke database:', err));
 
module.exports = sequelize;

Models

models/Users.js

const { DataTypes } = require('sequelize');
const sequelize = require('../config/db');
 
const User = sequelize.define('User', {
  nama: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false
  }
}, {
  tableName: 'users',
  timestamps: true    
});
 
module.exports = User;

CRUD

app.js

const express = require('express');
const bcrypt = require('bcrypt');
const User = require('./models/Users');
const sequelize = require('./config/db');
const app = express();
const PORT = process.env.PORT || 3000;
 
const SALT_ROUNDS = 10;
 
app.use(express.json());
 
app.get('/users', async (req, res) => {
  try {
    const users = await User.findAll({
      attributes: { exclude: ['password'] } 
    });
    res.json(users);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Server error saat mengambil data' });
  }
});
 
app.get('/users/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const user = await User.findByPk(id, {
      attributes: { exclude: ['password'] }
    });
 
    if (!user) {
      return res.status(404).json({ error: 'User tidak ditemukan' });
    }
 
    res.json(user);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Server error saat mengambil user' });
  }
});
 
app.post('/users', async (req, res) => {
  try {
    const { nama, email, password } = req.body;
 
    if (!nama || !email || !password) {
      return res.status(400).json({ error: 'nama, email, dan password wajib diisi' });
    }
 
    const existingUser = await User.findOne({ where: { email } });
    if (existingUser) {
      return res.status(409).json({ error: 'Email sudah terdaftar' });
    }
 
    const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);
 
    const user = await User.create({
      nama,
      email,
      password: hashedPassword
    });
 
    const userResponse = {
      id: user.id,
      nama: user.nama,
      email: user.email,
      createdAt: user.createdAt
    };
 
    res.status(201).json(userResponse);
  } catch (error) {
    console.error('Error saat membuat user:', error);
    if (error.nama === 'SequelizeValidationError' || error.nama === 'SequelizeUniqueConstraintError') {
      return res.status(400).json({ error: 'Data tidak valid' });
    }
    res.status(500).json({ error: 'Gagal membuat user' });
  }
});
 
app.put('/users/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { nama, email, password } = req.body;
 
    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({ error: 'User tidak ditemukan' });
    }
 
    if (email && email !== user.email) {
      const existingUser = await User.findOne({ where: { email } });
      if (existingUser) {
        return res.status(409).json({ error: 'Email sudah digunakan oleh user lain' });
      }
    }
 
    const updateData = {};
    if (nama !== undefined) updateData.nama = nama;
    if (email !== undefined) updateData.email = email;
 
    if (password !== undefined) {
      const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);
      updateData.password = hashedPassword;
    }
 
    await user.update(updateData);
 
    const userResponse = {
      id: user.id,
      nama: user.nama,
      email: user.email,
      updatedAt: user.updatedAt
    };
 
    res.json(userResponse);
  } catch (error) {
    console.error('Error saat memperbarui user:', error);
    if (error.name === 'SequelizeValidationError' || error.name === 'SequelizeUniqueConstraintError') {
      return res.status(400).json({ error: 'Data tidak valid' });
    }
    res.status(500).json({ error: 'Gagal memperbarui user' });
  }
});
 
app.delete('/users/:id', async (req, res) => {
  try {
    const { id } = req.params;
 
    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({ error: 'User tidak ditemukan' });
    }
 
    await user.destroy(); 
    res.status(204).send(); 
  } catch (error) {
    console.error('Error saat menghapus user:', error);
    res.status(500).json({ error: 'Gagal menghapus user' });
  }
});
 
app.listen(PORT, () => {
  console.log(`Server berjalan di http://localhost:${PORT}`);
});

Bila terjadi error silahkan coba pakai raw, json di postman

Karena di code kita pakai app.use(express.json());

Date: 12-10-2025