Search code examples
sortingsql-order-byprisma

Prisma multiple optional sort properties, orderBy


I am working on a GET-endpoint in my Prisma back-end to retrieve all tasks.

Currently, I want to add multiple sort options using sortBy

In my code below there are two sortBy options. However, I cannot seem to make both of them work, just the first object in the orderBy[] array.

router.get("/tasks", async (req, res) => {
  var currentPage = req.query.page || 1;
  const listPerPage = 45;
  const offset = (currentPage - 1) * listPerPage;

  var category = req.query.category;
  var sortQuery = req.query.sort;
  var sort = sortQuery.split("_");

  var idSortBy = "asc";
  var dateSortBy = "asc";

  if (sort !== undefined) {
    if (sort[0] === "id") {
      idSortBy = sort[1];
    } else {
      dateSortBy = sort[1];
    }
  }

  const allTasks = await prisma.task.findMany({
    orderBy: [
      {
        createdAt: dateSortBy,
      },
      {
        id: idSortBy,
      },
    ],
    where: { category: category },
    skip: offset,
    take: listPerPage,
  });

  res.json({
    data: allTasks,
    meta: { page: currentPage },
  });
});

Solution

  • I have found the solution where all sorting options are parsed to the orderBy in the findMany function.

    router.get("/tasks", async (req, res) => {
      var currentPage = req.query.page || 1;
      const listPerPage = 45;
      var offset = (currentPage - 1) * listPerPage;
    
      var category = req.query.category;
    
      var sort = req.query.sort.split("_");
      var orderByObject = {};
      orderByObject[sort[0]] = sort[1];
      var orderBySet = [orderByObject];
    
      const allTasks = await prisma.task.findMany({
        where: { category: category },
        skip: offset,
        take: listPerPage,
        orderBy: orderBySet,
      });
    
      res.json({
        data: allTasks,
        meta: { page: currentPage },
      });
    });