Search code examples
node.jsazureazure-storageazure-table-storageazure-node-sdk

What is the best way to get the latest record belonging to a partition key using the azure-storage node library?


Can someone recommend the best solution for getting the latest record belonging to a partition key when using the azure-storage library in Node? Since there is no .orderBy() option... what is the best approach?

In C# I would probably do something like:

var latestRecord = results.OrderByDescending(r => r.Timestamp).FirstOrDefault();

What would the equivalent be when using this node library for Table Storage?


Solution

  • We need to implement custom compare function to sort the results.

    tableService.queryEntities(tableName, query, null, function(error, result, response) {
      if (!error) {
          var latestRecord = result.entries.sort((a,b)=>{
              return new Date(b.Timestamp._) - new Date(a.Timestamp._);
          })[0])
     }});
    

    Results are decorated with Edm type, so we need b.Timestamp._.

    Timestamp: { '$': 'Edm.DateTime', _: 2018-10-26T07:32:58.490Z }

    If this format is somehow unpleasant, we can get entities without metadata from response. Need to set payloadFormat.

    tableService.queryEntities(tableName, query, null, {payloadFormat:azure.TableUtilities.PayloadFormat.NO_METADATA},function(error, result, response) {
      if (!error) {
          var latestRecord = response.body.value.sort((a,b)=>{
              return new Date(b.Timestamp) - new Date(a.Timestamp);
          })[0]
     }});