Skip to content

Instantly share code, notes, and snippets.

@dabit3
Last active November 7, 2022 10:17
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save dabit3/5dd7069c91e46ee015c828c5384edb0f to your computer and use it in GitHub Desktop.
Save dabit3/5dd7069c91e46ee015c828c5384edb0f to your computer and use it in GitHub Desktop.
Add a user to DynamoDB after signing up
var aws = require('aws-sdk')
var ddb = new aws.DynamoDB()
exports.handler = async (event, context) => {
let date = new Date()
if (event.request.userAttributes.sub) {
let params = {
Item: {
'id': {S: event.request.userAttributes.sub},
'__typename': {S: 'User'},
'username': {S: event.userName},
'email': {S: event.request.userAttributes.email},
'createdAt': {S: date.toISOString()},
'updatedAt': {S: date.toISOString()},
},
TableName: process.env.USERTABLE
}
try {
await ddb.putItem(params).promise()
console.log("Success")
} catch (err) {
console.log("Error", err)
}
console.log("Success: Everything executed correctly")
context.done(null, event)
} else {
console.log("Error: Nothing was written to DynamoDB")
context.done(null, event)
}
};
/*
GraphQL Schema
type User @model
@auth(rules: [
{ allow: groups, groups: ["Admin"] },
{ allow: owner, ownerField: "username", operations: [read] }
]) {
id: ID!
username: String!
email: String!
}
*/
/*
IAM permissions
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem"
],
"Resource": "arn:aws:dynamodb:region:id:table/name-env"
}
]
}
*/
@tklaas
Copy link

tklaas commented Apr 10, 2021

When using Amplify with DataStore for offline sync, two additional fields (_lastChangedAt and _version) have to be in the Item

Item: {
        'id': {S: event.request.userAttributes.sub},
        '__typename': {S: 'User'},
        'username': {S: event.userName},
        'email': {S: event.request.userAttributes.email},
        'createdAt': {S: date.toISOString()},
        'updatedAt': {S: date.toISOString()},
        '_lastChangedAt': {N: date.valueOf().toString()},  // timestamp
        '_version': {N: '1'},
},

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment