gpt4 book ai didi

node.js - 跳过环回中的删除操作,发送自定义响应对象

转载 作者:搜寻专家 更新时间:2023-11-01 00:01:06 24 4
gpt4 key购买 nike

我想覆盖 strongloop 中的默认删除操作,并用某种“软删除”替换它们,它只是将标志设置为已删除。到目前为止,我已经了解了原始操作,并且没有调用 next() 函数,该操作不允许对数据库进行操作。但它也没有发送任何响应状态。那么执行此操作或发送自定义响应对象的最佳方法是什么?

module.exports = function (Module) {
Module.observe('before delete', function(ctx, next) {
id = ctx.where['id'];
Module.update({id: id}, {deleted: true}, null);
//next(); // don't call next to avoid deleting
});

更新:不是解决方案,但至少它触发了对 API 的一些响应:

Module.observe('before delete', function(ctx, next) {
var id = ctx.where['id'];
Module.update({id: id}, {deleted: true}, null);

// dirty method to trigger response
var err = new Error(); // create new error object
err.statusCode = 204; // set response code to empty response
next(err);

});

最佳答案

编辑正确答案如下:

module.exports = function(Model) {
let app;
Model.once('attached', (a) => {
app = a;

const deleteById = Model.deleteById;

Model.deleteById = (id, options, cb) => {
Model.updateAll({id: id}, {
deletedAt: new Date(),
deletedBy: options.accessToken.userId,
});
cb(null,'deleted')
};

// ...
});
}

在 LB2 和 LB3 中,一种方法是使用操作钩子(Hook)。在相关的 model.js 文件中添加:

module.exports = function(Model) {
let app;
Model.once('attached', (a) => {
app = a;
Model.observe('before delete', (ctx, next) => {
Model.findById(ctx.where.id, (err, instance) => {
if (err) {
return next(err);
}
instance.deletedAt = new Date();

// ...
// other modifications to instance
// ...

// save this in the hookState to retrieve it in after delete hook
ctx.hookState.deletedModelInstance = instance;
next();
});
});

Model.observe('after delete', (ctx, next) => {
Model.replaceOrCreate(ctx.hookState.deletedModelInstance,
(err, instance) => {
if (err) {
console.log(
'An error occured while restoring data ' +
'from hookState after delete operation'
);
}
next();
});
});
});
}

关于node.js - 跳过环回中的删除操作,发送自定义响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32072601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com