2015-09-28 79 views
0

有时,我们需要在将响应JSON数据发送到客户端之前进行修改。例如:什么是格式化/定制远程响应的最佳方式?

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

我想获得GET /files/:id请求url属性,所以我定义原型的URL吸气剂。

//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' 
} 

非常感谢!

+0

这是一个真正的坏问题? – XXLIVE

回答

1

您可以使用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()

其他操作钩包括:

  • 访问
  • 之前保存
  • 保存之前删除
  • 后删除
  • 后装
  • 坚持
+1

考虑给你的答案增加一点解释,而不是仅仅做一个只有代码的帖子。这对OP和未来的读者来说可能会更有帮助。 – Serlite

+0

@Serlite现在快乐吗? :-) – conradj

+0

酷!谢谢。 = d – Serlite

相关问题