如何在AWS AppSync中查询关注的用户的所有帖子

时间:2018-10-03 00:37:03

标签: aws-appsync

我有一个使用DynamoDB作为后端的AWS Appsync应用。我有一个帖子表,每个帖子都有原始作者的用户名字段。我处于一种查询状态,希望查看他们关注的所有作者的帖子。

每个用户可以有多个帖子,每个用户可以关注多个用户。

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

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

我应该如何构造DynamoDB中的表,而AppSync中的AppSync解析器/架构可以实现此目的。

1 个答案:

答案 0 :(得分:1)

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 解析器:

{
    "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 解析器

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

$util.toJson($ctx.result.items)

关注帖子解析器

{
    "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 解析器

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

$util.toJson($ctx.result)

测试

enter image description here

UserTable

enter image description here

PostTable

enter image description here

关注表

enter image description here

现在我们可以按用户名和所有朋友的帖子查询所有帖子。
希望它会有所帮助:)