Search code examples
javascriptgraphqlsequelize.jsdataloader

How to use dataloader?


Im trying to figure this out.

I want to get all my users from my database, cache them and then when making a new request I want to get those that Ive cached + new ones that have been created.

So far:

const batchUsers = async ({ user }) => {
  const users = await user.findAll({});

  return users;
};

const apolloServer = new ApolloServer({
  schema,
  playground: true,
  context: {
    userLoader: new DataLoader(() => batchUsers(db)),// not sending keys since Im after all users
  },
});

my resolver:

    users: async (obj, args, context, info) => {
      return context.userLoader.load();
}

load method requiers a parameter but in this case I dont want to have a specific user I want all of them.

I dont understand how to implement this can someone please explain.


Solution

  • If you're trying to just load all records, then there's not much of a point in utilizing DataLoader to begin in. The purpose behind DataLoader is to batch multiple calls like load(7) and load(22) into a single call that's then executed against your data source. If you need to get all users, then you should just call user.findAll directly.

    Also, if you do end up using DataLoader, make sure you pass in a function, not an object as your context. The function will be ran on each request, which will ensure you're using a fresh instance of DataLoader instead of one with a stale cache.

    context: () => ({
      userLoader: new DataLoader(async (ids) => {
        const users = await User.findAll({
          where: { id: ids }
        })
    
        // Note that we need to map over the original ids instead of
        // just returning the results of User.findAll because the
        // length of the returned array needs to match the length of the ids
        return ids.map(id => users.find(user => user.id === id) || null)
      }),
    }),
    

    Note that you could also return an instance of an error instead of null inside the array if you want load to reject.