'AWS Amplify GraphQL CreateOrUpdate / Upsert mutation
Minor newbie with GraphQL so I'm a little bit lost here. How would I go about creating a CreateOrUpdate mutation/resolver for a model on AWS Amplify?
I'm running a lambda function after every user auth to hit a third party API and pull back relevant data to that user. The entities that come back may already be stored but related to another user. I'm assuming there's a better way than attempting to Create, catching an error and then attempting to Fetch & Update with the new user appended to the users field?!
type Event
@model
@auth(rules: [
{allow: public, provider: apiKey, operations: [read, create, update, delete]}
{allow: owner, ownerField: "users"}
])
@key(fields: ["venue", "date"])
{
id: ID!
venue: String!
date: AWSDate!
ref: String!
users: [String]!
}
Any help massively appreciated (even just good resources to read up on writing resolvers - looking at the generated Mutation.updateEvent.req.vtl file for inspiration is a bit intimidating)
Solution 1:[1]
You need to override the generated resolver for update mutation.
Just copy the content of the autogenerated resolvers and make some changes.
File name may look like this:
<project-root>/amplify/backend/api/<api-name>/build/resolvers/<TypeName>.<FieldName>.<req/res>.vlt
To override, copy this file to:
<project-root>/amplify/backend/api/<api-name>/resolvers/<TypeName>.<FieldName>.<req/res>.vlt
For example: amplify/backend/api/blog/build/resolvers/Mutation.updatePost.req.vtl
Then remove these line:
## Begin - key condition **
#if( $ctx.stash.metadata.modelObjectKey )
#set( $keyConditionExpr = {} )
#set( $keyConditionExprNames = {} )
#foreach( $entry in $ctx.stash.metadata.modelObjectKey.entrySet() )
$util.qr($keyConditionExpr.put("keyCondition$velocityCount", {
"attributeExists": true
}))
$util.qr($keyConditionExprNames.put("#keyCondition$velocityCount", "$entry.key"))
#end
$util.qr($ctx.stash.conditions.add($keyConditionExpr))
#else
$util.qr($ctx.stash.conditions.add({
"id": {
"attributeExists": true
}
}))
#end
That part of vtl code checks that the id on update mutation should exists.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Afdol Riski |
