2015-09-28 62 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

相關問題