0

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?

Jerry Liu
  • 17,282
  • 4
  • 40
  • 61
Dana Epp
  • 509
  • 1
  • 5
  • 13

1 Answers1

0

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]
 }});
Jerry Liu
  • 17,282
  • 4
  • 40
  • 61
  • BTW, one slight change you will need to make. To make sure the Timestamps can be parsed right make sure you cast 'a' and 'b' to any, and use Date().getTime() since the sort needs a number for the sort compare. Otherwise, works like a charm. – Dana Epp Oct 26 '18 at 21:56
  • @DanaEpp Thanks for the tip. I find a,b are cast to any by default and the subtraction of new Date() returns number as expected on my side. Do you come across any situation those syntax causes trouble? Thanks for your patience again. – Jerry Liu Oct 26 '18 at 23:52
  • I am using the latest Typescript compiler. Tsc would not compile until I explicitly set those. Works like a charm. So thanks again. – Dana Epp Oct 26 '18 at 23:54