Help us learn about your current experience with the documentation. Take the survey.

GraphQL API 垃圾邮件防护和 CAPTCHA 支持

如果模型可以通过 GraphQL API 修改,您还必须为所有可能修改可垃圾邮件化或垃圾邮件相关属性的 GraphQL mutations 添加支持。这 definitely 包括 CreateUpdate mutations,但也可能包括其他,例如那些与更改机密/公开标志相关的 mutations。

为 GraphQL mutations 添加支持

主要步骤如下:

  1. 在你的 mutation 中使用 include Mutations::SpamProtection

  2. perform_spam_check: true 传递给 Update Service 类构造函数。 在 Create Service 中默认设置为 true

  3. 创建或更新 Spammable 模型实例后,调用 #check_spam_action_response! 并将模型实例传递给它。此调用:

    1. 对模型执行必要的垃圾邮件检查。
    2. 如果检测到垃圾邮件:
      • 引发 GraphQL::ExecutionError 异常。
      • 通过 extensions: 参数将相关信息作为错误字段添加到响应中。 有关这些字段的更多详细信息,请参阅 GraphQL API 文档中关于 Resolve mutations detected as spam 的部分。

    如果您使用上面描述的标准 ApolloLink 或 Axios interceptor CAPTCHA 支持, 您可以忽略字段详细信息,因为它们会被自动处理。 如果您尝试直接使用 GraphQL API 处理失败的潜在垃圾邮件检查, 并使用已解决的 CAPTCHA 响应重新提交请求,这些字段就会变得相关。

例如:

module Mutations
  module Widgets
    class Create < BaseMutation
      include Mutations::SpamProtection

      def resolve(args)
        service_response = ::Widgets::CreateService.new(
          project: project,
          current_user: current_user,
          params: args
        ).execute

        widget = service_response.payload[:widget]
        check_spam_action_response!(widget)

        # 如果检测到可能的垃圾邮件,`#check_spam_action_response!` 会抛出异常,
        # 因此正常的 resolve 返回逻辑可以在下面继续。
      end
    end
  end
end

有关如何在 GraphQL API 中测试 CAPTCHA 行为的说明,请参阅 Exploratory Testing 部分。