可以使用 GraphQL 的 Resolver 来实现选择性返回数组成员。以下是示例代码:
假设有一个 Task 类型,其中包含一个数组属性 subtasks。现在需要根据一个 subtask 的属性 isComplete 来选择性地返回 Task 数组中的成员:
type Task {
id: ID!
name: String!
subtasks: [Subtask!]!
}
type Subtask {
id: ID!
name: String!
isComplete: Boolean!
}
type Query {
tasks: [Task!]!
}
type Mutation {
completeSubtask(id: ID!): Subtask!
}
const resolvers = {
Query: {
tasks: () => {
// 查询所有任务
},
},
Task: {
subtasks: (task, args, context, info) => {
// 在此处过滤 subtasks
return task.subtasks.filter(subtask => subtask.isComplete === true);
},
},
Mutation: {
completeSubtask: (parent, { id }, context, info) => {
// 更改 subtask 的 isComplete 属性
},
},
};
在 Task 类型的 Resolver 中可以使用 filter() 方法来筛选子任务,只返回 isComplete 为 true 的子任务。同时,可以实现一个 Mutation 来更新子任务的 isComplete 属性。