我正在为Graphql / AppSync使用AWS Amplify(前端使用Cli和Angular 7),想知道当超过10个项目时如何获取所有连接的项目吗?
假设我已经创建了一个schema.graphql,如下所示:
type User @model {
id: ID!
firstname: String
lastname: String
project: Project @connection(name: "ProjectUsers")
}
type Project @model {
id: ID!
title: String
task: String
members: [User] @connection(name: "ProjectUsers")
}
运行放大推送时,它会生成查询和变异。当运行带有项目ID(从生成的API.service.ts文件中)的GetProject查询时,它将返回具有已连接用户的Project项。但是,如果该项目的用户数超过10,则只会给我10个第一个用户和一个下一个令牌:
{
id: "67b1fc0a-fd1f-4e8b-9bd7-b82b2aea5d3b",
title: "Test",
task: "test",
members: {
items: {
0: {__typename: "User", id: "f245809a...}
1: ...
(2-8: ...)
9: ...
nextToken: "qwerj23r2kj....3223oop32kjo",
__typename: "ModelUserConnection";
}
}
__typename: "Project"
}
我可以看到多种解决方案,但是看不到如何解决:
是否可以更改schema.grapql来更改代码源,以便它可以生成更改限制的功能,例如。是100而不是标准的10?
使用nextToken从生成的API.service.ts文件中对结果进行分页吗?
更改schema.graphql文件,以便生成的ModelUserFilterInput具有userProjectId字段(在生成的ListUsers查询中使用)吗?
或者是否有其他解决方案可以通过自动生成的文件(API.service.ts)中的查询来获取项目的所有用户?
到目前为止,我能看到的唯一解决方案是首先运行ListUsers查询(不使用任何过滤器),然后遍历所有这些查询以检查其是否具有正确的项目ID。但是,如果用户数据库很大,则可能增长为大量数据,而且速度很慢,并且使用@connection的好处并不真正。
很抱歉很长一段时间,我希望我已经解释了足够的问题。
答案 0 :(得分:1)
A) Change your query
query {
getProjet(id: "123") {
id
members(limit: 50) {
items {
firstname
}
}
}
B) Attach a Resolver
In the AWS AppSync console, at the right end side of the Schema section. Filter by UserConnection
or similar find UserConnection.items and click Attach
.
1) DataSource: UserTable0
2) Request mapping template: ListItems
{
"version" : "2017-02-28",
"operation" : "Scan",
"limit": $util.defaultIfNull(${ctx.args.limit}, 50),
"nextToken": $util.toJson($util.defaultIfNullOrBlank($ctx.args.nextToken, null))
}
Use the limit coming as an argument ctx.args.limit
or if its null use 50
.
3) Response mapping template
$util.toJson($ctx.result.items)
By doing this you can change how the underlying table is being scanned/fetched.
C) Paginate
Another solution would be to paginate at the application level and leave the 10 items limit.
Note: I may be missing other solutions.
Update: to use this solution together with Amplify Console.
Now, you can update your resolvers locally and use the Amplify CLI to push the updates into your account. Here’s how it works.
After creating your AWS AppSync API, you will now have a new empty folder called resolvers created in your Amplify project in the API folder. To create a custom resolver, create a file (i.e. Query.getTodo.req.vtl) in the resolvers directory of your API project. The next time you run amplify push or amplify api gql-compile, your resolver template will be used instead of the auto-generated template. You may similarly create a Query.getTodo.res.vtl file to change the behavior of the resolver’s response mapping template.
<amplify-app>
|_ amplify
|_ .config
|_ #current-cloud-backend
|_ backend
|_ api
|_ resolvers
Query.getProject.req.vtl
Query.getProject.res.vtl
team-provider-info.json