Search code examples
aws-appsync

How to query for all posts by followed users in AWS AppSync


I have an AWS Appsync app using DynamoDB as a backend. I have a table for Posts and each post has an username field of the original author. I am in a situation where I want to query to view all post by authors which they are following.

Each User can have many Posts and each User can follow many User.

type Post {
    id: ID!
    username: String
    title: String
    content: String
}

type User{
     username: String
     following: [String]
}

How should I structure the tables in DynamoDB and the AppSync resolvers/schema in AppSync accomplish this.


Solution

  • type User {
        username: String! ## Primary key
        posts: [Post]
        following: [Following]
    }
    type Following {
        follower: String! ## Primary key
        username: String! ## Sort key
        posts: [Post]
    }
    type Post {
        username: String! ## Primary key
        postID: ID! 
        title: String
        content: String
    }
    type Query {
        getPostsByUsername(username: String!): User
    }
    schema {
        query: Query
    }
    

    User.posts resolver:

    {
        "version": "2017-02-28",
        "operation": "Query",
        "query": {
            "expression": "username = :username",
            "expressionValues": {
                ":username": $util.dynamodb.toDynamoDBJson($context.source.username)
            }
        }
    }
    
    $util.toJson($ctx.result.items)
    

    User.following resolver

    {
        "version": "2017-02-28",
        "operation": "Query",
        "query": {
            "expression": "follower = :follower",
            "expressionValues": {
                ":follower": $util.dynamodb.toDynamoDBJson($context.source.username)
            }
        }
    }
    
    $util.toJson($ctx.result.items)
    

    Following.posts resolver

    {
        "version": "2017-02-28",
        "operation": "Query",
        "query": {
            "expression": "username = :username",
            "expressionValues": {
                ":username": $util.dynamodb.toDynamoDBJson($context.source.username)
            }
        }
    }
    
    $util.toJson($ctx.result.items)
    

    Query.getPostsByUsername resolver

    {
        "version": "2017-02-28",
        "operation": "GetItem",
        "key": {
            "username": $util.dynamodb.toDynamoDBJson($ctx.args.username),
        }
    }
    
    $util.toJson($ctx.result)
    

    Testing

    enter image description here

    UserTable

    enter image description here

    PostTable

    enter image description here

    FollowingTable

    enter image description here

    Now we can query all posts by username and all friends's posts as well.
    Hope it is helpful :)