popular-magentaP
Refine17mo ago
9 replies
popular-magenta

useMany and REST API

Hello,

I would like to add the logic to my backend to make the useMany hook work.

Here is my Controller:
export const getMany: RequestHandler = async (req, res) => {
  const { ids } = req.query;
  console.log("ids", ids);
  const leagues = await crud("league").getMany(ids as string[]);
  res.json(leagues);
};

And here is my Mongo service:
export const database = client.db(config.MONGO_DB_NAME);
export const collection = <TCollection extends string>(name: TCollection) =>
  database.collection<DocumentFromCollection<TCollection>>(name);
export const crud = <TCollection extends string = keyof MongoCollections>(
  collectionName: TCollection
) => {
  const _collection = collection(collectionName);
  const log = logger.getChildLogger({ name: collectionName });
  return {
    collection: _collection,
    async list(opts?: {
      filter?: Filter<DocumentFromCollection<TCollection>>;
      pagination?: { start: number; end: number };
    }) {
      const cursor = _collection
        .find(opts?.filter ?? {})
        .skip(opts?.pagination?.start ?? 0)
        .limit(
          Math.min(
            opts?.pagination
              ? Math.max(opts.pagination.end - opts.pagination.start, 0)
              : MAX_DOCUMENTS,
            MAX_DOCUMENTS
          )
        );
      return {
        data: await cursor.toArray(),
        total: await _collection.countDocuments(opts?.filter ?? {}),
      };
    },
    async getMany(ids: string[]) {
      const objectIds = ids.map((id) => new ObjectId(id));
      const documents = await _collection
        .find({ _id: { $in: objectIds } } as Filter<
          DocumentFromCollection<TCollection>
        >)
        .toArray();
      return {
        data: documents,
      };
    },
  };
};


Here is the useMany hook that needs to be working:
const { data: leaguesData } = useMany<League[], HttpError>({
    resource: "leagues",
    ids: ["6697d1e2da0de8fd14940360"],
});


What is wrong with the code?
Was this page helpful?