如何使用JavaScript从Azure表存储中检索最新记录?

时间:2017-11-21 04:34:56

标签: javascript azure azure-table-storage

Image shows the azure table如何使用JavaScript从Azure表存储中检索最新记录?

我看到了这篇文章, How to retrieve latest record using RowKey or Timestamp in Azure Table storage

但我想在Nodejs服务器端实现相同,任何建议。 代码到目前为止,

 var dt = Date().toLocaleString();
      console.log("Got response: " + dt);

        var entGen = azure.TableUtilities.entityGenerator;
      var task = {
        PartitionKey: entGen.String('ConfigData'),
        RowKey: dt,
        DeviceId: entGen.String(req.body.devId),
      };

      // Insert the entity to the table
      tableSvc.insertEntity('configurationData', task, function (error, result, response) {
        if (!error) {
          // Entity inserted
          console.log("Added the data in table successfully");
        }
        else{
          console.log(error);
        }
      });

我得到了以下错误,

name: 'StorageError',
  message: 'The \'RowKey\' parameter of value \'11/21/2017, 8:17:24 AM\' is out of range.\nRequestId:687de370-0002-0055-09a1-62d5e1000000\nTime:2017-11-21T08:17:25.6350503Z',
  code: 'OutOfRangeInput',
  statusCode: 400,
  requestId: '687de370-0002-0055-09a1-62d5e1000000' }

提前致谢。

2 个答案:

答案 0 :(得分:1)

首先,您收到错误的原因是RowKey值包含/字符,这是不允许的。有关PartitionKeyRowKey属性的有效值,请参阅以下链接:https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-the-table-service-data-model

现在回答您关于如何检索最新记录的其他问题,正如您在问题中链接的答案中所提到的,您需要做的是确保实体获得prepended而不是{{1} }。要做到这一点,您可以获取当前时间的appended(您设置为当前Epoch seconds的值,并从最大纪元秒中减去该值。

例如,

RowKey

答案 1 :(得分:0)

除了上面的注释,您还可以简单地获取时期时间并从高数(100,000,000)中减去该时期并将该值设置为RowKey。这将逆转取回数据时返回的顶部记录。

var now = new Date()  
var secondsSinceEpoch = Math.round(now.getTime() / 1000)
var RowKey = 100000000 - secondsSinceEpoch;
public async updateEntity(table:string, body:any){
    
    var url = `${this.baseUrl}/${table}(PartitionKey='${body.PartitionKey}', RowKey='${body.RowKey}')?sv=${this.sv}`;
    var head = {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
        "X-Requested-With": "XMLHttpRequest",
        "Accept": "application/json;odata=nometadata",
        "Content-Type": "application/json"
    };
    
    var method = 'PUT';        
    var res = await fetch(url, {method: method, headers: head, body: JSON.stringify(body)});         
}

var body:any = {
        PartitionKey: "My Key",
        RowKey: `${RowKey}`
    }
this.updateEntity("tableName", body);