You can do the whole thing with a single UpdateItem operation:
const dynamodbParams = {
TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
Key: {id: userId},
UpdateExpression: 'SET createdAt = if_not_exists(createdAt, :ca)',
ExpressionAttributeValues: {
':ca': {'S': timestamp}
}
};
dynamoDb.updateItem(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log(data);
}
}
If you only want to do insert if not exists, you can easily do that with PutItem:
const dynamodbParams = {
TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
Item: {
id: userId,
createdAt: timestamp
},
ConditionExpression: 'attribute_not_exists(id)'
};
dynamodb.putItem(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log(data);
}
}
You can come up with more complex ways how to set or update attributes in an item by combining the condition expressions and update expressions.
Note I have not fully tested the code, so please comment if there's any error, but it should work.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…