Next.js Discord

Discord Forum

Vercel PostgreSQL ORDER BY query not working

Unanswered
Least Bittern posted this in #help-forum
Open in Discord
Least BitternOP
I am trying to do a project with the latest app router, @vercel/postgres, and making my api with the vercel server as well
I have the following function I use as a fetcher:
await fetch(
    `/api/bookings?sort_by=${sortParam}`
  )
    .then((res) => res.json())
    .then((data) => {
      bookings = data.bookings;
    })
    .catch((err) => {
      console.log(err);
    });

Where sortParam is a key from my client, which in my api/bookings route will be extracted like this:
// Get sorting filter from searchparams
  const { searchParams } = new URL(req.url);
  const sortBy = searchParams.get("sort_by")!;
  console.log(typeof sortBy, sortBy);

  const sorterMap = {
    "asc-arrival": "arrival_date",
    "desc-arrival": "arrival_date DESC",
    "asc-departure": "departure_date",
    "desc-departure": "departure_date DESC",
    "asc-guests-number": "guests_number",
    "desc-guests-number": "guests_number DESC",
  };

  let sorterClause =
    sorterMap[sortBy as keyof typeof sorterMap] || "arrival_date";

Now, the values in my sorterMap object will be my ORDER BY clause, like this:

const { rows: bookings } = await sql`SELECT 
      arrival_date, booking_id, departure_date, guests_number 
      FROM bookings 
      WHERE user_id=${userID} 
      ORDER BY ${sorterClause};`;


However, this doesn't work. I tried console.logging my sql statement and paste it into vercel's storage query space and it worked there, but it won't work when performing it as an API request.
What am i doing wrong? I checked and the type is string, I tried with and without DESC, I'm not really sure what I am doing wrong :/
I would really appreciate it if anyone could take a look, thank you

0 Replies