Skip to main content

GraphQL API 高级策略

¥Advanced policies for the GraphQL API

发送到 GraphQL API 的请求会经过 Strapi 的 middlewarespolicies 系统。可以将策略附加到解析器以实现复杂的授权规则,如本简短指南中所示。

¥Requests sent to the GraphQL API pass through Strapi's middlewares and policies system. Policies can be attached to resolvers to implement complex authorization rules, as shown in the present short guide.

有关 GraphQL 策略的更多信息,请参阅 GraphQL 插件配置 文档。

¥For additional information on GraphQL policies, please refer to the GraphQL plugin configuration documentation.

条件可见性

¥Conditional visibility

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

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

/src/policies/limit-public-results.ts
export default async (policyContext, config, { strapi }) => {
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:

/config/policies.ts
export default {
'api::restaurant.restaurant': {
find: [ 'global::limit-public-results' ],
},
};

群组成员资格

¥Group membership

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

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

/src/policies/is-group-member.ts
export default async ({ state }, config, { strapi }) => {
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:

/config/policies.ts
export default {
'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.