in lambda/index.js [121:152]
function setUrl(url, callback, salt) {
let id = computeId(url, salt);
const params = {
TableName: process.env.DDB_TABLE,
Item: {
id: { S: id },
target: { S: url }
},
// Ensure that puts are idempotent
ConditionExpression: "attribute_not_exists(id) OR target = :url",
ExpressionAttributeValues: {
":url": {S: url}
}
};
dynamodb.putItem(params, (err, data) => {
if (err) {
if(err.code === 'ConditionalCheckFailedException') {
console.warn('Collision on ' + id + ' for ' + url + '; retrying...');
// Retry with the attempted ID as the salt.
// Eventually there will not be a collision.
return setUrl(url, callback, id);
} else {
console.error('Dynamo error on save: ', err);
return done(500, JSON.stringify({error: 'Internal Server Error: ' + err}), 'application/json', callback);
}
} else {
return done(200, id, 'text/plain', callback);
}
});
}