Sorting
VitNode provide a sorting system to order the query result.
Here is an example of how to use the sorting system. We will use the core_members
table as an example.
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.
Data Transfer Object (DTO)
We will create a DTO
to create arguments values for the query.
Create a enum
Inside show/dto/show.args.ts
file create a enum to restrict the sorting columns.
enum ShowBlogCategoriesSortingColumnEnum {
created = "created",
updated = "updated"
}
Enum name should be unique. If you have multiple enums in the same file, make sure to give them unique names.
Remember to export the enum. It will be used in the next steps.
Register the enum
NestJS require to register the enum in the GraphQL schema. You can read more in NestJS documentation (opens in a new tab).
import { registerEnumType } from "@nestjs/graphql";
registerEnumType(ShowBlogCategoriesSortingColumnEnum, {
name: "ShowBlogCategoriesSortingColumnEnum"
});
Create a input type
Now you have to create a input type to use the enum in the args type.
import { InputType } from "@nestjs/graphql";
import { SortDirectionEnum } from "@/types/database/sortDirection.type";
@InputType()
class SortByArgs {
@Field(() => ShowBlogCategoriesSortingColumnEnum)
column: ShowBlogCategoriesSortingColumnEnum;
@Field(() => SortDirectionEnum)
direction: SortDirectionEnum;
}
Add input type to args type
Now you have to add the input type to the args type as arry and make it optional (If you want).
import { ArgsType, Field } from "@nestjs/graphql";
@ArgsType()
export class ShowCoreMembersArgs {
@Field(() => [SortByArgs], { nullable: true })
sortBy: SortByArgs[] | null;
}
Service
Inside service in show/show.service.ts
file you have to add the sortBy
argument to the show
method.
@Injectable()
export class ShowBlogCategoriesService {
constructor(private databaseService: DatabaseService) {}
async show({
cursor,
first,
last,
sortBy
}: ShowBlogCategoriesArgs): Promise<ShowBlogCategoriesObj> {
const pagination = await inputPaginationCursor({
cursor,
database: blog_categories,
databaseService: this.databaseService,
first,
last,
primaryCursor: { order: "ASC", key: "id", schema: blog_categories.id },
defaultSortBy: {
direction: SortDirectionEnum.asc,
column: "position"
},
sortBy
});
...
}