#sortBy query parameter doesn't work

4 messages · Page 1 of 1 (latest)

unborn knot
#

Hello everyone, currently I'm trying to perform find all methods with query params that included sortBy in the endpoint like this GET localhost:3000/api/v1/contacts?page=1&size=10&sortBy=asc

But the input cannot process to the query, because it's diferent type.
This is my query look like:

import { QueryOrder } from '@mikro-orm/core';
const sorting: Record<QueryOrder> = {};

if (searchReq.sortBy) {
const [field, direction] = searchReq.sortBy.split(':');
sorting[field] = direction === 'asc' ? QueryOrder.ASC : QueryOrder.DESC;
}

 const [contacts, totalContacts] = await this.contactRepository.findAndCount(
      {
        user: user.id,
        $and: filters,
      },
      {
        limit: searchReq.size,
        offset: (searchReq.page - 1) * searchReq.size,
        orderBy: { id: sorting },
      },
    )

the id in orderBy have type QueryOrderKeys<number> and must filled with QueryOrder.ASC that have type enum like this:

export enum QueryOrder {
ASC = "ASC",
ASC_NULLS_LAST = "ASC NULLS LAST",
ASC_NULLS_FIRST = "ASC NULLS FIRST",
DESC = "DESC",
}```

all of that imported from @mikro-orm/ core

if I make variabel like this and replace it on `sorting `variable: 
```ts
const asc = searchReq.sortBy === 'asc' ? QueryOrder.DESC : QueryOrder.ASC;

false expresstion will always that got read, even thought my input is asc or desc in sortBy query param.

Anyone know how to handle this problem?

granite tendon
#

From the code sample, you're assigning the entire "sorting" object to orderBy.id

#

Pretty sure you meant to assign it to the top-level orderBy

unborn knot
# granite tendon Pretty sure you meant to assign it to the top-level `orderBy`

thank you, finally it worked as I expected. I dont know why yesterday I cant assign const orderBy: Record<string, QueryOrder> = {}; to orderBy clause.

For now, I write it like this:

// list fields in the entity
    const metadata: EntityMetadata = this.orm.getMetadata().get(Contact.name);
    const validFields = Object.keys(metadata.properties);

    // Defaults sortBy and orderBy
    const defaultField = 'id';
    const defaultDirection = QueryOrder.ASC;

    // Split sortBy and orderBy by comma
    const sortFields = (searchReq.sortBy || defaultField).split(',');
    const sortDirections = (searchReq.orderBy || 'asc').split(',');

    // Construct the orderBy object
    const orderBy: Record<string, QueryOrder> = {};

    // Iterate through sortFields and match with sortDirections
    sortFields.forEach((field, index) => {
      const direction =
        sortDirections[index]?.toLowerCase() === 'desc'
          ? QueryOrder.DESC
          : QueryOrder.ASC;

      if (validFields.includes(field)) {
        orderBy[field] = direction;
      } else {
        console.warn(`Invalid sortBy field "${field}", skipping.`);
      }
    });

    // Log the constructed orderBy object
    console.log('Constructed orderBy:', orderBy);
    // ========================================
    const [contacts, totalContacts] = await this.contactRepository.findAndCount(
      {
        user: user.id,
        $and: filters,
      },
      {
        limit: searchReq.size,
        offset: (searchReq.page - 1) * searchReq.size,
        orderBy: orderBy,
      },
    );

thank you, really appreciate your help ❤️