Reasons to use Xrm.WebApi #1 - ETag magic

The Xrm.WebApi client-side SDK has been around for a while now, but you may still be using a hand-built HTTP request to call the WebApi from JavaScript/TypeScript.

ETag magic

Normally when you query the WebApi for a specific record you'll always get a JSON response back that contains the entity field values at the time of the query.

If your code queries the same record using the WebApi many times then this can introduce overhead that will slow down your code. To combat this, we often introduce elaborate caching schemes but this leads to the challenge of keeping the cache current.

The good news is that the Xrm.WebApi SDK already implements a cache for us inside the retreiveRecord call using the ETag.

Consider a call to retrieveRecord as follows:

Xrm.WebApi.retrieveRecord("account","<guid>","?$select=name,parentaccountid")
.then(function(a){console.log(a);})

The first call will retrieve the record from the server including the ETag value

{
    "@odata.context": "https://org.crm11.dynamics.com/api/data/v9.0/$metadata#accounts(name,parentaccountid)/$entity",
    "@odata.etag": "W/\"4400496\"",
    "name": "Sample Account Mon, 31 Dec 2018 10:36:56 GMT",
    "statecode@OData.Community.Display.V1.FormattedValue": "Active",
    "statecode": 0,
    "accountid": "120703f7-e70c-e911-a8c2-0022480173bb",
    "merged@OData.Community.Display.V1.FormattedValue": "No",
    "merged": false
}

The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved.

When you next query for the same record with the same $select attributes the client SDK will send the value of the Etag in the request header:

If-None-Match: W/"4400496"

If the record has not been modified since then the server will return:

HTTP/1.1 304 Not Modified

This indicates that the client side SDK can then reuse the same record that was retrieved previously.

Since it would be quite complex to implement this feature in your hand-build HTTP requests, this is indeed a good reason to use the Xrm.WebApi SDK!

Happy 2019! 😊

Comments (1) -

Comments are closed