var TableStore = require('tablestore');
var options = { accessKeyId: '你的accessKeyId', accessKeySecret: '你的accessKeySecret',}
var otsClient = new TableStore.Client({ accessKeyId: options.accessKeyId, secretAccessKey: options.accessKeySecret, endpoint: '你的endpoint', instancename: '你的instancename', maxRetries: 20 //默认20次重试,可以省略这个参数。});
var response = { isBase64Encoded: false, statusCode: 200};
module.exports.handler = function(event, context, callback) {
var eventJson = JSON.parse(event.toString()); var deviceId = eventJson.deviceName; var productKey = eventJson.productKey; var lastTime = new Date(eventJson.lastTime);
var params = { tableName: "device_status_table", primaryKey: [{ 'deviceId': deviceId },{'productKey': productKey}], maxVersions: 1 };
try { otsClient.getRow(params, function(err, data) { if (err) { response.body = { msg: 'error', code: 404 }; callback(null, response); return; } //有数据,拿出来比较lastTime if (data.row.primaryKey) { var attributes = data.row.attributes; var dbTime = ''; attributes.forEach(function(item) { if (item.columnName == 'lastTime') { dbTime = new Date(item.columnValue); } }) //转换成毫秒进行比较 if (lastTime.getTime() < dbTime.getTime()) {
return; } }
var iot_data = { tableName: "device_status_table", condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
primaryKey: [{ "deviceId": deviceId },{'productKey': productKey}],
attributeColumns: [ { 'lastTime': eventJson.lastTime }, { 'clientIp': eventJson.clientIp }, { 'status': eventJson.status } ],
returnContent: { returnType: TableStore.ReturnType.Primarykey } }
otsClient.putRow(iot_data, function(err, data) { if (err) { response.body = { msg: 'error', code: 404 }; callback(null, response); return; }
response.body = { msg: 'ok', code: 200 }; callback(null, response); return; });
});
} catch (err) { response.body = { msg: 'error', code: 404 }; callback(null, response); }
};
评论