【发布时间】:2020-11-27 04:41:48
【问题描述】:
我目前正在关注AWS Amplify docs,并且我正在使用默认博客 GraphQL 架构来尝试创建关系 Dynamo DB 表。
博客模型表显示在 DynamoDB 中,我可以向它们上传信息,但我不知道如何使它们具有关系。模型类型为 Blog 、 Post 和 Comment 。例如,在将帖子上传到其 DynamoDB 表后,如何将上传的评论链接到同一个帖子?在我的 Swift 代码中,我尝试这样做但无济于事。
我也不理解List<Comment>.init() 的语法,它可能不应该存在,但没有给出错误。也许这就是我的问题的原因。
创建帖子:
let blog = Blog(name: "UserBlog", posts: List<Post>.init())
let posts = Post(title: "Testing out AWS", blog:blog, comments: List<Comment>.init())
_ = Amplify.API.mutate(request: .create(posts)) { event in
switch event {
case .success(let result):
switch result {
case .success(let post):
print("Successfully created the post: \(post)")
case .failure(let graphQLError):
print("Failed to create graphql \(graphQLError)")
}
case .failure(let apiError):
print("Failed to create a todo", apiError)
}
}
调试控制台的输出
Successfully created the post: Post(id: "83D71F16-6B0D-453A-A163-AABF484CE527", title: "Testing out AWS", blog: nil, comments: nil)
然后在使用此代码为该帖子创建评论后
let blog = Blog(name: "UserBlog", posts: List<Post>.init())
let posts = Post(title: "Testing out AWS", blog:blog, comments: List<Comment>.init())
let comments = Comment(content: "It worked", post: posts)
_ = Amplify.API.mutate(request: .create(comments)) { event in
switch event {
case .success(let result):
switch result {
case .success(let comment):
print("Successfully created the comment: \(comment)")
case .failure(let graphQLError):
print("Failed to create graphql \(graphQLError)")
}
case .failure(let apiError):
print("Failed to create a todo", apiError)
}
}
调试控制台的输出
Successfully created the comment: Comment(id: "85395F8B-C8C2-4ACB-8FC5-DAEFC2728C32", content: Optional("It worked"), post: nil)
最后在使用此代码从表中获取之后
let post = Post.keys
let predicate = post.title == "Testing out AWS"
_ = Amplify.API.query(request: .list(Post.self, where: predicate)) { event in
switch event {
case .success(let result):
switch result {
case .success(let post):
print("Successfully retrieved list of posts: \(post)")
case .failure(let error):
print("Got failed result with \(error.errorDescription)")
}
case .failure(let error):
print("Got failed event with error \(error)")
}
}
调试控制台的输出
Successfully retrieved list of posts: [testAWS.Post(id: "83D71F16-6B0D-453A-A163-AABF484CE527", title: "Testing out AWS", blog: nil, comments: nil)]
如何将评论链接到帖子,以便在查询时显示评论而不是nil
我的架构:
type Blog @model {
id: ID!
name: String!
posts: [Post] @connection(name: "BlogPosts")
}
type Post @model {
id: ID!
title: String!
blog: Blog @connection(name: "BlogPosts")
comments: [Comment] @connection(name: "PostComments")
}
type Comment @model {
id: ID!
content: String
post: Post @connection(name: "PostComments")
}
【问题讨论】:
标签: swift amazon-web-services graphql amazon-dynamodb aws-amplify