format/customize 远程响应的最佳方式是什么?

What's the best way to format/customize the remote response?

有时,我们需要在发送给客户端之前修改响应JSON数据。例如:

//model definition
{
  "name": "File",
  "base": "PersistedModel",
  "properties": {
    "filename": {
      "type": "string",
      "required": true
    },
    "filepath": {
      "type": "string"
    }
  }
  "protected": ["filepath"]
}

我想在 GET /files/:id 请求上得到一个 url 属性,所以我在原型上定义了一个 url GETTER。

//file.js

module.exports = function(File){
  var baseUrl = 'http://example.com/uploads/files/';
  File.prototype.__defineGetter__('url', function(){
    return baseUrl + this.id.toString() + this.filename;
  });
}

我的问题是当我发出如下请求时,如何将 url 属性 暴露给远程响应?

GET /files/123456

期待这样的回应:

{
  id: '123456',
  filename: 'myfile.ext',
  url: 'http://example.com/uploads/files/123456/myfile.ext'
}

非常感谢!

您可以使用 Operation Hooks 独立于调用它们的特定方法拦截 CRUD 操作。

下面的代码将在加载 File 对象时将 url 属性 添加到 File 对象。

File.observe('loaded', function(ctx, next) {
  var baseUrl = 'http://example.com/uploads/files/';
  ctx.data.url = baseUrl + data.id + data.filename;

  next();
});

当以下任何方法被调用时,这将被调用,无论是直接在您的 JS 中还是通过 HTTP 间接调用 API。

  • 查找()
  • findOne()
  • findById()
  • 存在()
  • 计数()
  • 创建()
  • upsert()(与 updateOrCreate() 相同)
  • findOrCreate()
  • prototype.save()
  • prototype.updateAttributes()

其他操作挂钩包括:

  • 访问
  • 保存前
  • 保存后
  • 删除前
  • 删除后
  • 已加载
  • 坚持

使用遥控器 method/hook 并相应地自定义您的响应。参见 https://github.com/strongloop/loopback-example-app-logic/blob/master/common/models/car.js