json API 中的计算字段?

Calculated fields in json API?

我想知道我们应该向哪个扩展添加 API 值,这些值可以根据原始数据和额外的可用信息(来自浏览器会话、用户界面......或其他)计算

例如,我们可以有一个 API 返回这个 JSON:

{
    ownder_id: '123',
    canAddComment: true,
    etc...
}

这直接给了我们值 "canAddComment"。 或者我们可以这样:

{
    ownder_id: '123',
    etc...
}

其中,评论可以从owner_id开始计算。例如,如果会话 owner_id 与从 API 收到的不同,用户可以添加评论。

我们本可以在 Javascript 中完成此操作:

//supposing we have a session object with our browser session values
var params = {owner_id: session.owner_id};
$.post(apiURL, params, function(data){
    var result = JSON.parse(data);

    //processing the data
    result["canAddComments"] = result.owner_id !== session.owner_id;

    //do whatever with it
});

最好的方法是什么?在这种情况下有什么建议?

我不确定你想知道什么。但我的第一反应是你用它做一个函数。

// constructor
function Comment() {
  this.owner_id;
  this.canAddComment = function() {
    return session.user_id === this.owner_id;
  }
}

var session = {
  user_id: 22,
  name: 'Kevin'
};

var my_comment = new Comment();
my_comment.owner_id = 15;
if(my_comment.canAddComment()) {
  $.ajax({
    // now read the form and submit the data ...
  })
}
else {
  alert('Only the author of this message can update ...');
}

编辑:

My question was mainly if this should better be calculated in the backend side or calculated after retrieving the API data.

不确定是否有通用答案。一些论点:如果您希望该方法是秘密的,则必须在服务器端进行。在其他情况下,我认为让客户端 PC 使用其处理能力非常有意义。

好吧,一个例子:排序。假设有一个 table 充满了数据;单击头部可根据该列对 table 进行排序。将所有数据发送到服务器,让它对 table 和 return 键数组进行排序是否有意义?不,我认为让客户处理这个更有意义。 http://tablesorter.com/docs/

与Google地图类似:您将标记拖到某个地方,然后程序必须计算出最近的 5 个公交车站。好吧,显然你在客户端计算了所有这些。