gpt4 book ai didi

ruby-on-rails - 如何通过 :current_user in Graphql resolver

转载 作者:行者123 更新时间:2023-12-04 03:44:11 25 4
gpt4 key购买 nike

我有查询类型

Types::QueryType = GraphQL::ObjectType.define do
name 'Query'

field :allProjects, function: Resolvers::Projects
end

像这样的解析器
require 'search_object/plugin/graphql'

module Resolvers
class Projects
include SearchObject.module(:graphql)

type !types[Types::ProjectType]

scope { Project.all }

ProjectFilter = GraphQL::InputObjectType.define do
name 'ProjectFilter'

argument :OR, -> { types[ProjectFilter] }
argument :description_contains, types.String
argument :title_contains, types.String
end

option :filter, type: ProjectFilter, with: :apply_filter
option :first, type: types.Int, with: :apply_first
option :skip, type: types.Int, with: :apply_skip

def apply_first(scope, value)
scope.limit(value)
end

def apply_skip(scope, value)
scope.offset(value)
end

def apply_filter(scope, value)
branches = normalize_filters(value).reduce { |a, b| a.or(b) }
scope.merge branches
end

def normalize_filters(value, branches = [])
scope = Project.all
scope = scope.where('description ILIKE ?', "%#{value['description_contains']}%") if value['description_contains']
scope = scope.where('title ILIKE ?', "%#{value['title_contains']}%") if value['title_contains']
branches << scope

value['OR'].reduce(branches) { |s, v| normalize_filters(v, s) } if value['OR'].present?
branches
end
end
end

我想在解析器中访问 c​​urrent_user,这样我就可以访问 current_user.projects 而不是 Project.all。我对graphql和学习很陌生。

一切正常,但我只需要了解如何让解析器中的 ctx 变老的整个流程。

最佳答案

首先你需要设置current_user在上下文中。这发生在您的 GraphqlController 中。

class GraphqlController < ApplicationController
before_action :authenticate_user!

def execute
variables = ensure_hash(params[:variables])
query = params[:query]
operation_name = params[:operationName]
context = {
current_user: current_user,
}
result = HabitTrackerSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
render json: result
rescue => e
raise e unless Rails.env.development?
handle_error_in_development e
end

# ...
end
完成后,您可以访问 current_user从查询(或突变)只需编写:
context[:current_user]
为了使事情更简单,您可以添加 current_user方法 Types::BaseObject ( app/graphql/types/base_object.rb ),您可以调用 current_user来自 #resolve方法。
module Types
class BaseObject < GraphQL::Schema::Object
field_class Types::BaseField

def current_user
context[:current_user]
end
end
end

关于ruby-on-rails - 如何通过 :current_user in Graphql resolver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51957480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com