Node.js - MySQL 타임스탬프 관리

Jangmyun·2024년 7월 19일

타임스탬프를 MySQL 레벨에서 관리

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  deleted_at TIMESTAMP NULL
);
이러면 mysql2 를 사용해서 데이터 삽입 시 created_atupdated_at를 제외하고 INSERT 쿼리 실행 가능함
const mysql = require('mysql2');

const pool = mysql.createPool({
  host: 'localhost',
  user: 'your-username',
  password: 'your-password',
  database: 'your-database'
});

const promisePool = pool.promise();

const addUser = async (name) => {
  const [result] = await promisePool.execute(
    'INSERT INTO users (name) VALUES (?)', 
    [name]
  );
  return result;
};

const express = require('express');
const app = express();
app.use(express.json());

app.post('/users', async (req, res) => {
  try {
    const { name } = req.body;
    const result = await addUser(name);
    res.status(201).json({ id: result.insertId });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

0개의 댓글