在特定情况下删除我的 json 字段

Remove a field of my json in a specific case

本文关键字:字段 json 我的 删除 在特定情况下      更新时间:2023-09-26

我有一个列出所有用户的 ExpressJS 控制器

userCtrl.get

get(req, res, next) {
  var func = function(err, data) {
    if (err) return next(err);
    return res.json(data);
  };
  if (req.params[this.idName])
    this._getById(req.params[this.idName], func);
  else
    this._getAll(func);
  }
  _getById(id, fn) {
    this.ObjectClass.findById(id, fn);
  }
  _getAll(fn) {
    this.ObjectClass.findAll(fn);
  }

我想从另一条路上调用它,这样 res.json() 将过滤这个 json 的一个字段像这样:

router.get ('/services/:serviceKey/authBridge/users', function(req, res, next) {
  function anonJs(x) {
    x.forEach(s => s.credential = null);
    res.json(x);
  }
  res.json = anonJs;
  userCtrl.get(req, res, next);
});

问题是,在最后一段代码中,我最终得到了一个递归,因为我称之为res.json现在定义为anonJS

在替换旧函数之前,必须存储对旧函数的引用。

router.get ('/services/:serviceKey/authBridge/users', function(req, res, next) {
  var json = res.json;
  res.json = function(x) {
    x.forEach(s => s.credential = null);
    json(x);
  }
  userCtrl.get(req, res, next);
});