问题
I'm trying to implement GraphQL filter using Amplify GraphQL Client. I got a list of todos and wanted to retrieve list of todos that has status complete.
The Documentation only show how to get all items and single item
const allTodos = await API.graphql(graphqlOperation(queries.listTodos));
console.log(allTodos);
Could someone please point me how to apply filter to the listTodos so that it return todos with status complete only.
I tried to do the following but it is wrong.
API.graphql(graphqlOperation(queries.listTodos(filter: {
status: {
eq: "completed"
}
})));
回答1:
I think I have an answer to your question, but I also have a similar question regarding the AWS Amplify codegen queries, mutations, etc. If you look at the code that was generated inside of ~/graphql folder, you'll find a declaration file similar to this:
export const listOrganizations = `query ListOrganizations(
$filter: ModelOrganizationFilterInput
$limit: Int
$nextToken: String
) {
listOrganizations(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
id
name
address
}
nextToken
}
}
`;
You can see here that the first parameter to the ListOrganizations query (in your case, ListTodos query) takes a first argument of filter: $filter. I have figured out so far that you can modify this query by doing the following...
API.graphql(graphqlOperation(queries.listTodos, {
filter: {
status: {
eq: "completed"
}
}
})));
This should filter out all Todos except the ones where their status is equal to completed. The problem that I am having is that I want to enable different levels of access control such that anyone with a Cognito User Pool Group of Admin may view @model as well as the @owner. And I was able to get this all working using the @auth transformer, but now my problem is that on some screens, I only want to display certain entities that are the owner of that entity and because I am also an Admin, the API defaults to getting me everything. I want to use this @filter or ModelOrganizationFilterInput to only give me the data where I am the owner. The only way I have found to do this was to add the owner field to my Schema, but then the API always provides the owner field and I want to filter that field out.
The only documentation that I can find on how the aws-amplify API and graphqlOperation methods is here: https://aws-amplify.github.io/docs/js/api but there are not many examples and they don't show much of how the API works on the client. I'm stuck.
来源:https://stackoverflow.com/questions/53947508/how-to-do-filteration-in-aws-amplify-graphql-client