@elchinabilov/nestjs-reorder
v1.1.0
Published
A NestJS package created with nestjs-packager
Readme
@elchinabilov/nestjs-reorder
A NestJS package that provides reorder functionality for TypeORM entities.
Features
- ✅ Universal reorder functionality
- ✅ Automatic sortOrder assignment (via subscriber)
- ✅ Group-based sorting support
- ✅ Full TypeORM integration
- ✅ TypeScript support
Installation
npm install @elchinabilov/nestjs-reorder
# or
pnpm add @elchinabilov/nestjs-reorder
# or
yarn add @elchinabilov/nestjs-reorderRequirements
- Node.js >= 18.0.0
- NestJS
- TypeORM ^0.3.27
Usage
1. Import the module
import { Module } from "@nestjs/common";
import { ReorderModule } from "@elchinabilov/nestjs-reorder";
@Module({
imports: [ReorderModule.forRoot()],
})
export class AppModule {}2. Define static fields in your entity
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class Task {
static reorderGroupField = "projectId"; // Group field
static reorderOrderField = "sortOrder"; // Order field (default: 'sortOrder')
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
projectId: string;
@Column({ default: 0 })
sortOrder: number;
@Column()
title: string;
}3. Use in your service
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { ReorderService, ReorderDto } from "@elchinabilov/nestjs-reorder";
import { Task } from "./task.entity";
@Injectable()
export class TaskService {
constructor(
@InjectRepository(Task)
private readonly taskRepository: Repository<Task>,
private readonly reorderService: ReorderService
) {}
async reorderTask(dto: ReorderDto): Promise<void> {
await this.reorderService.reorder(this.taskRepository, dto);
}
}4. Create an endpoint in your controller
import { Controller, Post, Body } from "@nestjs/common";
import { ReorderDto } from "@elchinabilov/nestjs-reorder";
import { TaskService } from "./task.service";
@Controller("tasks")
export class TaskController {
constructor(private readonly taskService: TaskService) {}
@Post("reorder")
async reorder(@Body() dto: ReorderDto) {
await this.taskService.reorderTask(dto);
return { success: true };
}
}API
ReorderDto
{
itemId: string; // ID of the item being moved
overId: string; // ID of the item it's being moved over
}ReorderService
reorder<T>(repo: Repository<T>, dto: ReorderDto): Promise<number>
Reorders an item and returns the new sortOrder value.
Automatic sortOrder
When a new entity is created, ReorderSubscriber automatically assigns the sortOrder value. If sortOrder is already set, the subscriber will not modify it.
Notes
reorderGroupFieldandreorderOrderFieldstatic fields must be defined in the entityreorderGroupFieldcan be an array (for priority selection)- Sorting works with a step of 1000 (STEP)
- All operations are performed within a transaction
Author
Elchin Abilov
- Email: [email protected]
License
ISC
