Search code examples
aws-appsync

How to create a GraphQl resolver for Appsync for "most likes"


Im using AWS Appsync with DynamoDB as it data source. I have 2 tables, one for Photos and one for Likes. In a Appsync resolver I want to return only photos with more than 5 likes. How can I achieve this in Appsync

Schema

type Photo {
    id: ID!
    likes: [LikedPhoto]
}

type LikedPhoto {
    id: ID!
    username: String!
    photoId: String!
}

Query

type Query {
    listPhotos(filter: PhotoFilterInput, limit: Int, nextToken: String): PhotoConnection
}

Photo Resolver

Data Source: PhotoTable

{
  "version": "2017-02-28",
  "operation": "Scan",
  "filter": #if($context.args.filter) $util.transform.toDynamoDBFilterExpression($ctx.args.filter) #else null #end,
  "limit": $util.defaultIfNull($ctx.args.limit, 20),
  "nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.nextToken, null)),
}

Likes Resolver

Data Source: LikesTable

{
    "version": "2017-02-28",
    "operation": "Query",
    "index": "photoId-index",
    "query": {
        "expression": "photoId = :photoId",
        "expressionValues": {
            ":photoId": {
                "S": "$context.source.id"
            }
        }
    }
}

How can i write a resolver for likes or photos, to only show photos that have more than 5 likes.


Solution

  • How about designing your schema like a document-based to have only PhotoTable.
    So you can easily filter photos with totalLike.

    type Photo {
      id: ID!
      likedUsername: [String]
      totalLike: Int
    }
    
    // QUERY RESOLVER
    {
        "version" : "2017-02-28",
        "operation" : "Scan",
        "filter" : {
            "expression": "totalLike > :totalLike",
            "expressionValues": {
                ":totalLike": {
                    "N": 5
                }
            }
        }
    }