dataloadgen icon indicating copy to clipboard operation
dataloadgen copied to clipboard

How to handle resolver for field with Array type?

Open fresonn opened this issue 1 year ago • 2 comments

For example we have:

# schema.graphql
type Todo {
  id: ID!
  text: String!
  done: Boolean!
  users: [User!]
}

type User {
  id: ID!
  name: String!
}
# gqlgen.yml
models:
  Todo:
    fields:
      users:
        resolver: true

In regular case I need a loader like this:

func (t *todoLoader) todoUsers(ctx context.Context, todoIDs []string) ([]User, []error) {...}

Function for gqlgen resolver

func GetTodoUsers(ctx context.Context, todoID string) ([]User, error) {
	loaders := For(ctx)
        // I can't use .Load() because it returns T not []T
	return loaders.TodoLoader.LoadAll(ctx, []string{productID})
}

But when todoUsers() returns the users slice []User with len > 1 there is always an error:

"message": "bug in loader: 2 values returned for 1 keys"

How can I get in result something like this?

{
  "id":"1",
  "text":"...",
  "done":false,
  "users":[
    {
      "id":"1",
      "name":"Bob"
    },
    {
      "id":"2",
      "name":"Alice"
    }
  ]
}

fresonn avatar Mar 27 '24 12:03 fresonn

Your fetch function should return [][]User, not []User. Each of the returned results is interpreted as a response to the query for one key.

vikstrous2 avatar Apr 05 '24 15:04 vikstrous2

Yes, it next case question. How can I use "many to one" case for now? For example, I have a single entity query with loader.Load(): ID --> []T{T, T, T} Field resolver gets one entity "id"

I think I am on wrong way... Could you provide an example here: https://github.com/vikstrous/dataloadgen-example

fresonn avatar Apr 08 '24 17:04 fresonn

any updates 🥺?

fresonn avatar Dec 05 '24 21:12 fresonn

The input to the fetch function of a loader is a list of IDs and the output is the objects for those IDs. It's not expected to map between different types of objects.

vikstrous avatar Dec 07 '24 20:12 vikstrous

If I'm not understanding the question, please add an example to help me understand. I'll close for now.

vikstrous avatar Mar 08 '25 17:03 vikstrous

The answer is that you need to work with T[][] with pre-sorting in the dataloader.

fresonn avatar Mar 09 '25 10:03 fresonn