Incrementing and Decrementing Numeric Attributes GraphQL
See original GitHub issueWhich Category is your question related to? GraphQL
Amplify CLI Version 4.13.1
What AWS Services are you utilizing? Cognito, AppSync, DynamoDB, API Gateway, Lambda
Is it possible to increment or decrement a number in a graph model like you can do with the dynamodb SET Update Expression (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.SET.IncrementAndDecrement)?
For example I have this model:
type ResetHistory @model @auth(
rules: [ {allow: owner} ])
{
id: ID!
resetCount: Int!
totalResetTime: Float!
}
I currently have a function that updates the dynamodb table directly using the following command:
...[snip]
const params = {
TableName: `ResetHistory-${apiGraphQLAPIIdOutput}-${environment}`,
Key: {
id: unmarshalledNewRecord.id
},
UpdateExpression: 'SET resetCount = resetCount + :count, totalResetTime = totalResetTime + :resetTime',
ExpressionAttributeValues: {
":count": 1,
":resetTime": parseFloat(resetTimeMinutes)
},
};
try {
//Write updates to agg table
await documentClient.update(params).promise();
....[more code below]
This works but I need to create a subscription on this data for my app so I am looking to rewrite the function to execute an AppSync function (updateResetHistory) so it can trigger subscriptions. Is there a way to accomplish the same increment functionality within the amplify framework?
At the end of the day I really just need to set a field = field + [some number] but I am not seeing anything in the docs. I have been reading over posts about custom resolvers. Is that the only way to get this to work?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:10 (2 by maintainers)
So I ended up creating a custom Mutation to do this. I made it pretty generic so it should help others. It’s not great - but it is a start and should be able to help people. I have left out the authentication and some other boilerplate included with the default update Mutation. You can copy it from what is generated in the
amplify/backend/api/<ApiName>/build/resolvers/Mutation.<operation>.req.vtl
. You should see where to start inserting this code by looking at the boilerplate. You will want to put your custom file atamplify/backend/api/<ApiName>/resolvers/Mutation.<operation>.req.vtl
so it gets built every time you build the graphql schema.The code looks at the values provided and instead of overwriting numbers will add them to the value that is already there. So if you pass
5
it will add5
to whatever value is already in the field. It works with negative numbers as well. The caveat is that ALL NUMERIC FIELDS ARE ADDITIVE. There is no way to simply override the value with these operations.Is this not possible with Amplify? It is such a simple operation to not be able to do.