Sequelize destroy function not return instance of deleted row

50 Views Asked by At
exports.deleteCustomer = asyncHandler(async (req, res) => {
    const id = req.params.id;

    if (!id) {
        res.status(400).send({ message: "can't remove ,invalid customer" });
        return
    }

    try {
        const data = await Customer.destroy({ where: { id: id } })
        console.log(data, id, "deleteone")
        res.status(200).json(data);
    } catch (error) {
        res.status(400);
        throw new Error(error.message || "can't remove Customer");
    }
})

This is how I called in postman http://localhost:5000/customerManager/customer/5

console say 1 5 deleteone

postman response is 1

how can i get that instance value

1

There are 1 best solutions below

0
Bench Vue On

The delete code you provided is functional and can delete a customer record from the database.

Response Format: The response format for a successful DELETE operation is typically an acknowledgment message or an empty response body. Returning the deleted data might be confusing, as it's not a common practice for DELETE requests. Instead, you can return a simple success message.

For a successful DELETE operation, the most appropriate HTTP status code to use is 204 No Content. This status code indicates that the request was successfully processed, and there is no additional content to include in the response body. It communicates that the resource has been deleted without returning any data.

While you can use a 200 OK status code with a response body to convey additional information about the deleted resource, it is not as standard or explicit as 204 No Content for DELETE operations. It may also introduce some ambiguity, as clients might expect a response body with data when a 200 status code is used.

The HTTP 204 No Content status code is defined to indicate that a request has been successfully processed, but there is no content to return in the response body. According to the HTTP specification, when a server responds with a 204 No Content status code, it should not include a message body.

You need to change your server code for deleting.

exports.deleteCustomer = asyncHandler(async (req, res) => {
    const id = req.params.id;

    if (!id) {
        res.status(400).json({ message: "Invalid customer ID" });
        return;
    }

    try {
        const customer = await Customer.findById(id);

        if (!customer) {
            res.status(404).json({ message: "Customer not found" });
            return;
        }

        await Customer.destroy({ where: { id: id } });

        // Respond with a 200 OK status code along with a success message and deleted customer's ID
        res.status(200).json({ message: "Customer deleted successfully", deletedCustomerId: id });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

Demo code

Using SQLites and sequelize.js

Save as 'create_database.js'

const { Sequelize } = require('sequelize');
const path = require('path');

const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: path.join(__dirname, 'database.sqlite'),
});

async function createDatabase() {
  try {
    await sequelize.authenticate();
    await sequelize.sync({ force: true }); // Drops and recreates tables
    console.log('SQLite database created successfully.');
  } catch (error) {
    console.error('Error creating SQLite database:', error);
  } finally {
    sequelize.close();
  }
}

createDatabase();

Install dependencies

npm install body-parser cors express express-async-handler sequelize sqlite3

Create Database

node create_database.js 

enter image description here

Server

Save as server.js

const express = require('express');
const bodyParser = require('body-parser');
const { Sequelize, DataTypes } = require('sequelize');
const asyncHandler = require('express-async-handler');
const cors = require('cors');
const path = require('path'); // Import the path module

const app = express();
const port = 5000;

const sequelize = new Sequelize({
    dialect: 'sqlite', // Use SQLite as the dialect
    storage: path.join(__dirname, 'database.sqlite'), // Define the SQLite database file path
});

const Customer = sequelize.define('Customer', {
    name: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
    },
});

app.use(cors());
app.use(bodyParser.json());

// Create a customer
app.post('/customer', asyncHandler(async (req, res) => {
    try {
        const customer = await Customer.create(req.body);
        res.status(201).json({ message: 'Customer created successfully', customerId: customer.id });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
}));

// Read all customers
app.get('/customer', asyncHandler(async (req, res) => {
    const customers = await Customer.findAll();
    res.status(200).json(customers);
}));

// Read one customer by ID
app.get('/customer/:id', asyncHandler(async (req, res) => {
    const id = req.params.id;
    const customer = await Customer.findByPk(id);
    if (!customer) {
        res.status(404).json({ message: 'Customer not found', customerId: customer.id });
    } else {
        res.status(200).json(customer);
    }
}));

// Update a customer by ID
app.put('/customer/:id', asyncHandler(async (req, res) => {
    const id = req.params.id;
    const updatedCustomer = req.body;
    try {
        const customer = await Customer.findByPk(id);
        if (!customer) {
            res.status(404).json({ message: 'Customer not found' });
        } else {
            await customer.update(updatedCustomer);
            res.status(200).json({ message: 'Customer updated successfully', customerId: customer.id });
        }
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
}));


// Delete a Customer by ID
app.delete('/customer/:id', asyncHandler(async (req, res) => {
    const id = req.params.id;
    if (!id) {
        res.status(400).json({ message: "Can't remove, invalid customer" });
        return;
    }

    try {
        const customer = await Customer.findByPk(id);
        if (!customer) {
            res.status(404).json({ message: 'Customer not found' });
        } else {
            const deletedCustomerId = customer.id; // Store the deleted customer's ID
            await customer.destroy();
            res.status(200).json({ message: 'Customer deleted successfully', deletedCustomerId });
        }
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
}));


sequelize.sync()
    .then(() => {
        console.log('Database synchronized.');
        app.listen(port, '127.0.0.1', () => { // Specify IPv4 localhost
            console.log(`Server is running on IPv4 localhost at http://127.0.0.1:${port}`);
        });
    })
    .catch((error) => {
        console.error('Database synchronization error:', error);
    });

Run server

node server.js

Result

Using DB Browser for SQLite

enter image description here

API testing by Postman

Create customer

POST  http://localhost:5000/customer

Body data

{
  "name": "Steve Jobs",
  "email": "[email protected]"
}

enter image description here

Get customer

GET  http://localhost:5000/customer/1

enter image description here

Update customer

PUT  http://localhost:5000/customer/1

Body data

{
  "name": "Elon Musk",
  "email": "[email protected]"
}

enter image description here

Delete customer

DELETE  http://localhost:5000/customer/1

enter image description here