Created
September 24, 2020 03:12
-
-
Save damiancipolat/c0909c95c132fcba063afa0135d70053 to your computer and use it in GitHub Desktop.
An example of make a dynamic object update using dinamodb and nodejs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWS = require('aws-sdk'); | |
//Define aws region | |
AWS.config.update({ | |
region:'us-east-1' | |
}); | |
const TABLE = 'dc_test'; | |
//Get aws dynamo client instance. | |
const docClient = new AWS.DynamoDB.DocumentClient(); | |
//Register data in dynamodb table. | |
const update = (params)=> docClient.update(params).promise(); | |
//Make the query with partial values. | |
const partialUpdate = (table, key, object)=>{ | |
//Create params. | |
let query = { | |
TableName: table, | |
Key: key, | |
UpdateExpression: '', | |
ExpressionAttributeValues: {} | |
}; | |
//Get object keys. | |
const keys = Object.keys(client); | |
//Fill expresion attribute values. | |
let expAttrib={}; | |
keys.forEach(e=>expAttrib[`:${e}`]=client[e]); | |
//Fill update expression. | |
let updExpression=''; | |
keys.forEach((val,i)=>{ | |
if (i<keys.length-1) | |
updExpression=updExpression+`${val}=:${val},`; | |
else | |
updExpression=updExpression+`${val}=:${val}`; | |
}); | |
//Complete values. | |
query.ExpressionAttributeValues=expAttrib; | |
query.UpdateExpression=`SET ${updExpression}`; | |
return query; | |
} | |
//Lambda handler. | |
const run = async (object) => { | |
//Make the dynamic query by the object keys. | |
const query = partialUpdate('dc_test', {'user_id':'1234'}, object); | |
//Run update. | |
const result = await update(query); | |
console.log('query',query); | |
console.log('result',result); | |
return result; | |
}; | |
const client = { | |
email:'damian.cipolat@gmail.com', | |
google:{ | |
avatar:"www.damian.com", | |
email:"damian.cipolat@gmail.com", | |
name:"sssssssssssss" | |
}, | |
document:{ | |
firstName:'Damian', | |
lastName:'Cipolat', | |
number:'332955215', | |
address:'Opa opa', | |
gender:'M', | |
birthdate:'1987-10-06', | |
country:'ARGENTINA', | |
nationality:'ARGENTINA', | |
expiration:'2987-10-06', | |
fiscalNumber:'2033295515' | |
}, | |
legal:{ | |
fatca:false, | |
ddjj:false, | |
pep:false | |
}, | |
phone:{ | |
country:"+54", | |
number:"1166587382", | |
validatedAt:"2019-01-'01" | |
}, | |
signedTyc:{ | |
date:"01/01/01", | |
version:"1.0" | |
}, | |
account:{ | |
opRerenceId:"123124343243243232324" | |
} | |
}; | |
run(client); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment