Search code examples
kendo-uiteleriktelerik-appbuildereverlive

Fetching multiple levels of objects with kendo ui datasource?


I'm very new to developing mobile applications with telerik appbuilder. There are some things I have a hard time to understand with fetching data from Everlive.

Lets consider a simple example. Lets say I have Blog Posts and Comments that belong to those Posts. And both Posts and Comments are made by Users.

In one view I want to present the Post with corresponding Comments and I also need the Username of the User who posted the Comment (Comment table only contains userId).

Both the Post and the Comments are easy to fetch since I have the id of the Post. But how do I fetch the corresponding user for each Comment?

The FriendsApp example does something very similar but it uses this line to get the user:

var user = $.grep(app.Users.users(), function (e) {
   return e.Id === userId;
})[0];

This fetches all users and filters them client side? I guess this is okay if you have like 10 users. But what if you have a million users?


Solution

  • I am guessing that the FriendsApp uses this way of resolving the relations just for keeping the simplicity of the sample. Everlive offers a far more meaningful toolset for resolving relation fields called Expand. You can explore the REST API here:

    http://docs.telerik.com/platform/backend-services/development/rest-api/relations/simple-expanding

    or the JS SDK function here:

    http://docs.telerik.com/platform/backend-services/development/javascript-sdk/relations/simple-expanding.

    As the Friends app uses the Kendo UI data source component you can send an Expand header with the request. The following configuration of the data source will return the DisplayName of the user in each Activity/Comments entity:

    var expandObject = { 
        "CreatedBy": { 
            "ReturnAs": "User", 
            "SingleField": "DisplayName" 
        } 
    };
    
    var dataSource = new kendo.data.DataSource({ 
        type: "everlive", 
        transport: { 
            typeName: 'Activities', // replace this with Comments 
            read: { 
                beforeSend: function (xhr) { 
                    xhr.setRequestHeader("X-Everlive-Expand", JSON.stringify(expandObject)) 
                }, 
            } 
        }, 
        schema: { 
            model: { 
                id: Everlive.idField 
            } 
        } 
    }); 
    
    dataSource.fetch(function (data) { 
        console.log(data.items); 
    }); 
    

    Same could be applied for resolving the comments for each Blog post. Given the Friends data schema you will need to use the External Relation resolver of the Everlive API. Note that it is available only in a GetById scenario, e.g. when retrieving an Activity by Id, you can resolve the Comments that point to this activity, which is generally very handy in master-detail views.