1

I have a data loader that resolves the different values of an item

export const Item: ItemResolvers = {
  id: async (item) => item.id,
  weight: async (item) => {
    const finalItem = await dataLoader.Item.load(item.id);
    return finalItem.weight;
  },
  name: async (item) => {
    const finalItem = await dataLoader.Item.load(item.id);
    return finalItem.name;
  },
  image: async (item) => {
    const finalItem = await dataLoader.Item.load(item.id);
    return finalItem.image;
  },
};

I want to filter items with a particular name. Initially, I only have ids of the items. But, I am not able to figure out how can i filter out items after dataloader has loaded the names of the items.

Chandrika
  • 101
  • 1
  • 1
  • 9
  • do you want to filter by id, and name ? like ```dataLoader.Item.load({ id: "ABC", name: "something" }) ``` – FatihAziz Mar 07 '23 at 14:47

1 Answers1

0

This is a bit tricky, as you would have to resolve all item names before filtering. If there is any way to do the filtering on the parent query level, I would highly suggest to do that. If you can only get the full list, you can use Dataloader.loadMany():

const itemsResolver = async (parent, args) => {
  // adopt to your own setup:
  const nameFilter = args.filter.name;
  const items = await loadItems();
  // Use the dataloader to load all items in the array
  const finalItems = await dataLoader.Item.loadMany(items.map(item => item.id));

  // It seems to be okay to filter the finalItems array in your case:
  return finalItems.filter(item => item.name.includes(nameFilter));
  // But if you want to return items with only the "id" property, we can filter the
  // initial items array with this trick: Since we know that the finalItems contains
  // exactly the items in order, we can use the index to get the matching finalItem
  return items.filter((_, index) => finalItems[index].name.includes(nameFilter));
}
Herku
  • 7,198
  • 27
  • 36