VitNode
Database

Sorting

How to sort data in VitNode.

In some cases, you may need to sort the data in the database. VitNode provides a sorting system to order the query result.

Pagination Required

Sorting system is based on Pagination System. If you don't want to use the pagination system you can use the orderBy argument directly in the findMany() method.

Create enum

First, you need to create an enum type in shared folder to define the sorting options.

apps/shared/plugins/{your_plugin_code}/example.emun.ts
export enum ShowExampleWelcomeSortEnum {
  created_at = "created_at",
  updated_at = "updated_at"
}

Enum should be defined outside file of class with types. Read more here Enums in DTO.

Extend query DTO

Next, you need to extend the query DTO to include the sorting options. Create sortBy and sortDirection properties in the query DTO and mark them as optional.

apps/shared/plugins/{your_plugin_code}/example.dto.ts
import { SortDirectionEnum } from "vitnode-backend/utils/pagination.enum";
import { ShowExampleWelcomeSortEnum } from "./example.enum";
 
export class ShowExampleWelcomeQuery extends PaginationQuery {
  @ApiPropertyOptional({
    enum: ShowExampleWelcomeSortEnum
  })
  @IsEnum(ShowExampleWelcomeSortEnum)
  @IsOptional()
  sortBy?: ShowExampleWelcomeSortEnum;
 
  @ApiPropertyOptional({ enum: SortDirectionEnum })
  @IsEnum(SortDirectionEnum)
  @IsOptional()
  sortDirection?: SortDirectionEnum;
}

Usage in service

Finally, you can use the sorting options in the service to sort the data.

apps/backend/src/plugins/{your_plugin_code}/example.service.ts
@Injectable()
export class ExampleWelcomeService {
  constructor(private readonly databaseService: DatabaseService) {}
 
  async show({
    first,
    last,
    cursor,
    sortBy, 
    sortDirection
  }: ShowExampleWelcomeQuery): Promise<ShowExampleWelcomeObj> {
    const pagination = await this.databaseService.paginationCursor({
      cursor,
      database: core_languages,
      first,
      last,
      sortBy, 
      sortDirection, 
      defaultSortBy: {
        direction: SortDirectionEnum.desc,
        column: "updated_at"
      },
      query: async (args) => await this.databaseService.db.query.core_languages.findMany(args)
    });
 
    return pagination;
  }
}

Frontent integration

Frontend API

You can read how to implement Sorting API here.

On this page