3

Where

class FindRecord < GraphQL::Function
  ...
  argument :id, !types.ID
  ...
end

this variation of a field definition within a GraphQL::ObjectType.define block works without error:

 field 'd1', DirectoryType, function: FindRecord.new(:directory) 

But for the same query this fails with the error message "Field 'd2' doesn't accept argument 'id'":

field 'd2', DirectoryType do                                                                                
  function FindRecord.new(:directory)                                                               
end      

After those fields are defined, for both d1 and d2 the value of target.fields['d?'].function is the same (with different object ids). But it looks like in the block version the function doesn't get applied to the field.

It also doesn't work when I skip the field helper and define the field like this:

target.fields[name] = GraphQL::Field.define {
  ...
  function FindRecord.new(:directory)
  ...
}

Am I calling the function method wrong? Any suggestions appreciated.

Mori
  • 27,279
  • 10
  • 68
  • 73

1 Answers1

1

You probably want to use resolve in the block instead of function (which is an option to the field method, and not a helper available on the block):

field 'd2', DirectoryType do                                                                                
  resolve FindRecord.new(:directory)                                                               
end   

because Functions usually implement the same call(obj, args, ctx) method, then they can be considered Callables and you should be able to use it with the resolve helper instead of the usual way:

field :students, types[StudentType] do
  argument :grade, types.Int
  resolve ->(obj, args, ctx) {
    Student.where(grade: args[:grade])
  }
end
elyalvarado
  • 1,226
  • 8
  • 13
  • But then the arguments in the function don't get applied and have to be added separately to each field. – Mori Apr 24 '18 at 06:57
  • Well, they should be added because `FindRecord.new(:directory).call` as receives the same arguments. If they are not getting applied then you might try: `resolve ->(obj, args,ctx) { FindRecord.new(:directory).call(obj, args,ctx) }` – elyalvarado Apr 24 '18 at 22:13
  • This didn't solve the problem, but it was the only attempt and a reasonable one, so awarding the bounty. Thank you @elyalvarado. – Mori Apr 24 '18 at 22:58