Search code examples
aws-amplifyaws-appsync

AWS Amplify AppSync @function on a model field


I'm creating an Amplify Schema for a blog that looks something like this:

 type Post @model {
   id: ID!
   caption: String!
   src: String!
 }

I want to add a new field in the Post model to calculate the number of times a Post was liked. It gets this data from a different API.

Is there a way to run a function on a model field only something like this.

 type Post @model {
   id: ID!
   caption: String!
   src: String!
   likes: String @function("getLikesLambda-${dev}")
 }

How would the getLikesLambda code look? I've seen code on the official documentation on implementing resolvers but all of them tie the @function to type query which is not exactly what I'm looking for.

Let me know if you guys have any suggestions or if anything is unclear.


Solution

  • Your resolver can be attached to any field, not only on the Query root

    I have implemented something similar

    On your graphQL schema:

      likes: String @function(name: "getLikesLambda-${env}")
    

    Add a new lambda function calling amplify function add

    And then write your code, here is a Python example, but you can use any language supported.

    import boto3
    
    def handler(event, context):
      print('received event:')
      print(event)
    
      if 'typeName' in event and event['typeName'] == 'Post' and event['fieldName'] == 'likes':
        print("Resolve field likes")
        # Do your logic to get the likes
        likes = getLikes()
        return likes
    
      return ''