I am doing an update operation on a DynamoDB item using AWS AppSync GraphQL mutations and I want all the values of the item after the update operation returned via the API after a successful update.
The item updates perfectly fine & I've also specified the ReturnedValues
attribute with ALL_NEW
which should return all of the attributes however Item.Id
is null
for some reason?.
GraphQL:
type User {
id: ID!
name: String
avatarUrl: String
createdAt: String
updatedAt: String
}
type Mutation {
updateUser(userId: ID!, name: String, avatarUrl: String): User
}
mutation updateUser {
updateUser(userId:"USER-14160000000", name:"Test Test", avatarUrl:"www.test.com") {
id
name
avatarUrl
createdAt
updatedAt
}
}
Lambda function which updates the item:
const AWS = require("aws-sdk")
AWS.config.update({ region: "ca-central-1" })
const dynamoDB = new AWS.DynamoDB.DocumentClient()
async function updateUser(userId, name, avatarUrl) {
var params = {
TableName: "Bol-Table",
Key: {
"pk": userId,
"sk": 'USER',
},
UpdateExpression: 'SET details.displayName = :name, details.avatarUrl = :avatarUrl, details.updatedAt = :updateDate',
ExpressionAttributeValues: {
':name': name,
':avatarUrl':avatarUrl,
':updateDate': new Date().toISOString()
},
ReturnValues: 'ALL_NEW'
};
const Item = await dynamoDB.update(params).promise();
console.log(Item);
return {
id: Item.pk,
name: Item.displayName,
avatarUrl: Item.avatarUrl,
createdAt: Item.createdAt,
updatedAt: Item.updatedAt
};
}
module.exports = updateUser;
GraphQL output from the updateUser
call:
{
"data": {
"updateUser": null
},
"errors": [
{
"path": [
"updateUser",
"id"
],
"locations": null,
"message": "Cannot return null for non-nullable type: 'ID' within parent 'User' (/updateUser/id)"
}
]
}
Output of console.log(Item)
from Amazon CloudWatch:
2021-10-10T17:47:39.338Z d06b7a58-541e-456f-b830-1a50eea7c35a INFO {
Attributes: {
sk: 'USER',
details: {
avatarUrl: 'www.test.com',
createdAt: '2021-10-10T16:40:25.455Z',
displayName: 'Test',
updatedAt: '2021-10-10T17:47:38.586Z'
},
pk: 'USER-16040000000'
}
}
Why am I receiving the error, Cannot return null for non-nullable type: 'ID' within parent 'User' (/updateUser/id)
?
CodePudding user response:
The AWS documentation for UpdateItem
shows that the attribute values are returned in a nested Attributes
object within the response.
{
"Attributes": {
"string" : {
"B": blob,
"BOOL": boolean,
"BS": [ blob ],
"L": [
"AttributeValue"
],
"M": {
"string" : "AttributeValue"
},
"N": "string",
"NS": [ "string" ],
"NULL": boolean,
"S": "string",
"SS": [ "string" ]
}
},
...
}
So you will need to access them using Item.Attributes
, as opposed to trying to access them on Item
as they don't exist at that level.
This should work:
return {
id: Item.Attributes.pk,
name: Item.Attributes.details.displayName,
avatarUrl: Item.Attributes.details.avatarUrl,
createdAt: Item.Attributes.details.createdAt,
updatedAt: Item.Attributes.details.updatedAt
};