카테고리 없음

node.js CRUD

kyunghoonk00k 2023. 6. 12. 13:21
반응형
// Require Dependencies
const mysql = require('mysql');
const express = require('express');
const app = express();

app.use(express.json());

// Configure Database Connection
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'your_password',
    database: 'your_database'
});

// Connect to MySQL database
connection.connect((error) => {
    if (error) {
        console.error('Error connecting to the MySQL server:', error);
        return;
    }
    console.log('Connected to the MySQL server');
});

// Error Handling Middleware
app.use((error, req, res, next) => {
    res.status(500).send({
        error: 'An error occurred while processing your request.',
        details: error.message
    });
});

// CREATE - (POST) Add new user
app.post('/users', (req, res, next) => {
    const newUser = req.body;
    const query = "INSERT INTO users SET ?";
    
    connection.query(query, newUser, (error, result) => {
        if (error) return next(error);
        
        res.send({ message: `User added with ID: ${result.insertId}` });
    });
});

// READ - (GET) Fetch all users
app.get('/users', (req, res, next) => {
    const query = "SELECT * FROM users";

    connection.query(query, (error, result) => {
        if (error) return next(error);
        
        res.send(result);
    });
});

// READ - (GET) Fetch user by ID
app.get('/users/:id', (req, res, next) => {
    const id = req.params.id;
    const query = "SELECT * FROM users WHERE id = ?";

    connection.query(query, id, (error, result) => {
        if (error) return next(error);
        if (result.length === 0) {
            return res.status(404).send({ error: `User with ID: ${id} not found` });
        }
        
        res.send(result);
    });
});

// UPDATE - (PUT) Update user by ID
app.put('/users/:id', (req, res, next) => {
    const id = req.params.id;
    const updatedUser = req.body;
    const query = "UPDATE users SET ? WHERE id = ?";
    
    connection.query(query, [updatedUser, id], (error, result) => {
        if (error) return next(error);
        if (result.affectedRows === 0) {
            return res.status(404).send({ error: `User with ID: ${id} not found` });
        }
        
        res.send({ message: `User updated with ID: ${id}` });
    });
});

// DELETE - (DELETE) Delete user by ID
app.delete('/users/:id', (req, res, next) => {
    const id = req.params.id;
    const query = "DELETE FROM users WHERE id = ?";

    connection.query(query, id, (error, result) => {
        if (error) return next(error);
        if (result.affectedRows === 0) {
            return res.status(404).send({ error: `User with ID: ${id} not found` });
        }
        
        res.send({ message: `User deleted with ID: ${id}` });
    });
});

// Start Server
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});
반응형