GraphQL猫鼬使用Dataloader限制批处理结果

时间:2018-10-24 03:51:05

标签: javascript node.js mongodb mongoose graphql

我在用户和照片之间有关联。每当我为所有用户获取信息时,我也都希望为每个用户获取前5张照片。 这是我的架构:

type User {
  id: ID!
  username: String!
  email: String!
  photos: [Photo!]!
}

type Photo {
  id: ID!
  url: String
  thumb: String
  name: String
  postedBy: User!
}

type Query {
  allUsers: [User!]!
}

所以在我的解析器中,我有:

{
  Query: {
    allUsers: async (parent, args, { models }) => {
      return await models.User.find();
    }
  },
  User: {
    photos: async (parent, args, { models, loaders }) => {
      return loaders.photoLoader.load(parent.id);
    }
  }
}

因此,使用数据加载器,我可以在一个请求中批处理所有照片,但是我找不到一种方法来限制每个用户的照片数量。

const batchPhotos = async (ids) => {
  const { models: { Photo, User } } = db;

  const photos = await Photo.find({ postedBy: ids });

  // Something like Photo.find({ postedBy: ids }).limit(5) will bring 
  // first 5 results. I need to grab the first 5 for each user.

  const photoById = keyBy(photos, 'postedBy');

  return ids.map(id => photoById[id]);
}

export const photoLoader = () => new DataLoader(batchPhotos);

0 个答案:

没有答案