AWS Amplify AppSync @function on a model field

Viewed 841

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.

2 Answers

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 ''

@danielfranca is totally right. I haven't tested it yet but I recently found some documentation that I hadn't seen before here: https://docs.amplify.aws/cli/graphql-transformer/directives. There is an example here for functions which has this:

type Query {
    posts: [Post] @function(name: "GraphQLResolverFunction")
}
type Post {
    id: ID!
    title: String!
    comments: [Comment] @function(name: "GraphQLResolverFunction")
}
type Comment {
    postId: ID!
    content: String
}
Related