要解决“Amplify GraphQL不遵守我的查询限制”的问题,您可以使用以下代码示例来实现查询限制。
假设您有一个名为"Posts"的数据模型,其中包含"content"和"author"字段。您希望限制查询结果仅返回特定作者创建的帖子。
您可以使用@auth指令结合自定义规则来实现此目的。以下是一个示例:
touch directives.graphql
directive @auth(
rules: [AuthRule]
) on OBJECT | FIELD_DEFINITION
input AuthRule {
allow: AllowRule
and: [AuthRule]
or: [AuthRule]
not: AuthRule
}
input AllowRule {
operations: [String]
ownerField: String
identityField: String
groups: [String]
}
enum AuthStrategy {
owner
groups
private
public
}
directive @model(
queries: ModelQueries
mutations: ModelMutations
subscriptions: ModelSubscriptions
) on OBJECT
input ModelQueries {
get: AuthStrategy
list: AuthStrategy
sync: AuthStrategy
}
input ModelMutations {
create: AuthStrategy
update: AuthStrategy
delete: AuthStrategy
}
input ModelSubscriptions {
onCreate: AuthStrategy
onUpdate: AuthStrategy
onDelete: AuthStrategy
}
type Post @model(queries: { get: public, list: public }) @auth(rules: [{ allow: { ownerField: "author", identityField: "cognito:username" } }]) {
id: ID!
content: String!
author: String!
}
import { API, graphqlOperation } from 'aws-amplify';
const listPosts = async () => {
const filter = {
author: {
eq: "特定作者的ID"
}
};
const result = await API.graphql(graphqlOperation(`
query ListPosts($filter: ModelPostFilterInput) {
listPosts(filter: $filter) {
items {
id
content
author
}
}
}
`, { filter }));
console.log(result.data.listPosts.items);
}
listPosts();
在上面的示例中,我们使用"listPosts"查询,并将"filter"参数设置为特定作者的ID。这将限制查询结果仅返回特定作者创建的帖子。
请确保将"特定作者的ID"替换为您要限制查询的作者的实际ID。
使用上述代码示例,您可以确保Amplify GraphQL遵守您的查询限制,并仅返回特定作者创建的帖子。