# GraphQL 的高级策略

> Source: https://strapi.nodejs.cn/cms/api/graphql/advanced-policies

🌐 Advanced policies for the GraphQL API

策略可以附加到 GraphQL 解析器上以实现复杂的授权规则，例如限制未认证用户的结果或根据组成员身份限制访问。

🌐 Policies can be attached to GraphQL resolvers to implement complex authorization rules, such as limiting results for unauthenticated users or restricting access based on group membership.

发送到 [GraphQL API](/cms/api/graphql) 的请求会通过 Strapi 的 [middlewares](/cms/backend-customization/middlewares.md) 和 [policies](/cms/backend-customization/policies.md) 系统。策略可以附加到解析器上，以实现复杂的授权规则，如本短指南所示。

🌐 Requests sent to the [GraphQL API](/cms/api/graphql) pass through Strapi's [middlewares](/cms/backend-customization/middlewares.md) and [policies](/cms/backend-customization/policies.md) system. Policies can be attached to resolvers to implement complex authorization rules, as shown in the present short guide.

有关 GraphQL 策略的更多信息，请参阅 [GraphQL 插件配置](/cms/plugins/graphql#extending-the-schema) 文档。

🌐 For additional information on GraphQL policies, please refer to the [GraphQL plugin configuration](/cms/plugins/graphql#extending-the-schema) documentation.

## 条件可见性 {#conditional-visibility}

🌐 Conditional visibility

要限制未经身份验证的用户返回的条目数量，你可以编写一个修改解析器参数的策略：

🌐 To limit the number of returned entries for unauthenticated users you can write a policy that modifies resolver arguments:

```ts title="/src/policies/limit-public-results.ts"

  const { state, args } = policyContext;

  if (!state.user) {
    args.limit = 4; // only return 4 results for public
  }

  return true;
};
```

在 `/config/policies.ts` 中注册策略并将其应用到解析器：

🌐 Register the policy in `/config/policies.ts` and apply it to a resolver:

```ts title="/config/policies.ts"

  'api::restaurant.restaurant': {
    find: [ 'global::limit-public-results' ],
  },
};
```

## 群体成员资格 {#group-membership}

🌐 Group membership

策略可以访问 `policyContext.state.user` 来检查组成员身份，如以下示例所示：

🌐 Policies can access `policyContext.state.user` to check group membership, as in the following example:

```ts title="/src/policies/is-group-member.ts"

  const userGroups = await strapi.query('plugin::users-permissions.group').findMany({
    where: { users: { id: state.user.id } },
  });
  return userGroups.some(g => g.name === config.group);
};
```

使用以下配置的策略：

🌐 Use the policy with the following configuration:

```ts title="/config/policies.ts"

  'api::restaurant.restaurant': {
    find: [{ name: 'global::is-group-member', config: { group: 'editors' } }],
  },
};
```

在这个设置下，解析器只有在已认证用户属于 `editors` 组时才返回结果。

🌐 With this setup the resolver only returns results if the authenticated user belongs to the `editors` group.
