Sequelize 销毁函数不返回已删除行的实例

问题描述 投票:0回答:1
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");
    }
})

这就是我在邮递员中调用的方式http://localhost:5000/customerManager/customer/5

控制台说 1 5 删除一个

邮递员回复是1

我怎样才能获得该实例值

sequelize.js delete-row
1个回答
0
投票

您提供的删除代码有效,可以从数据库中删除客户记录。

响应格式:成功的

DELETE
操作的响应格式通常是确认消息或空响应正文。返回已删除的数据可能会令人困惑,因为这不是 DELETE 请求的常见做法。相反,您可以返回一条简单的成功消息。

对于成功的 DELETE 操作,最合适使用的 HTTP 状态代码是 204 No Content。此状态代码表示请求已成功处理,并且响应正文中无需包含其他内容。它表明资源已被删除,但没有返回任何数据。

虽然您可以使用带有响应正文的 200 OK 状态代码来传达有关已删除资源的附加信息,但对于 DELETE 操作,它不如 204 No Content 那样标准或明确。它还可能会引入一些歧义,因为当使用 200 状态代码时,客户端可能期望包含数据的响应正文。

HTTP 204 定义无内容状态码,表示请求已成功处理,但响应正文中没有内容可返回。根据 HTTP 规范,当服务器响应 204 No Content 状态代码时,它不应包含消息正文。

您需要更改服务器代码才能删除。

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 });
    }
});

演示代码

使用 SQLitessequelize.js

另存为“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();

安装依赖项

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

创建数据库

node create_database.js 

服务器

另存为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);
    });

运行服务器

node server.js

结果

使用 SQLite 数据库浏览器

Postman 的 API 测试

创建客户

POST  http://localhost:5000/customer

身体数据

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

获取客户

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

更新客户

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

身体数据

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

删除客户

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

© www.soinside.com 2019 - 2024. All rights reserved.