gpt4 book ai didi

ruby-on-rails - GraphQL Ruby : How to write DRY mutations with multiple parameters?

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

我正在写 devise-jwt我的 graphql-ruby 的基于身份验证系统使用应用程序。在这个过程中,我为创建一个新的用户帐户做了一个突变,它需要 7 个参数,这在我的代码中造成了很多重复:

module Mutations
class SignUpMutation < Mutations::BaseMutation
argument :email, String, required: true
argument :password, String, required: true
argument :family_name, String, required: true
argument :family_name_phonetic, String, required: true
argument :given_name, String, required: true
argument :given_name_phonetic, String, required: true
argument :newsletter_optin, Boolean, required: false

field :token, String, null: true
field :user, Types::UserType, null: true

def resolve(email:, password:,
family_name:, family_name_phonetic:,
given_name:, given_name_phonetic:,
newsletter_optin:
)
result = {
token: nil,
user: nil
}
new_user = User.new(
email: email,
password: password,
family_name: family_name,
family_name_phonetic: family_name_phonetic,
given_name: given_name,
given_name_phonetic: given_name_phonetic,
newsletter_optin: newsletter_optin
)
if new_user.save!
result[:token] = new_user.token
result[:user] = new_user
end
result
end
end
end

我怎样才能干掉它以避免在整个地方重复突变参数的名称?

提前谢谢你!

最佳答案

回答我自己的问题。不必处理这么多参数的正确方法是使用输入对象而不是单独的参数。来自 the graphql-ruby documentation :

Input object types are complex inputs for GraphQL operations. They’re great for fields that need a lot of structured input, like mutations or search fields.

所以我已经这样定义了我的输入对象:

module Types
class UserAttributes < Types::BaseInputObject
description 'Attributes for creating or updating a user'
argument :email, String, required: true
argument :password, String, required: true
argument :family_name, String, required: true
argument :family_name_phonetic, String, required: true
argument :given_name, String, required: true
argument :given_name_phonetic, String, required: true
argument :newsletter_optin, Boolean, required: false
end
end

然后像这样重构我的突变:

module Mutations
class SignUpMutation < Mutations::BaseMutation
argument :attributes, Types::UserAttributes, required: true

field :token, String, null: true
field :user, Types::UserType, null: true

def resolve(attributes:)
result = {
token: nil,
user: nil
}
new_user = User.new(attributes.to_hash)
if new_user.save!
result[:token] = new_user.token
result[:user] = new_user
end
result
end
end
end

最后,这段代码感觉更像 ruby​​ :)

关于ruby-on-rails - GraphQL Ruby : How to write DRY mutations with multiple parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59060696/

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