Abstract repository and other database tools for Nest and Sequelize.js ORM
npm install @nestlize/repositoryAbstract repository pattern implementation for Sequelize ORM in NestJS projects.
- Quick start
- Purpose
- Methods
- Configuration
Supports:
* ✅ Custom DTO typing or Sequelize creation attributes
* ✅ Custom error handling
* ✅ Soft delete support (paranoid: true)
* ✅ Pagination
* ✅ Optional UUID auto-generation
* ✅ Injected logger
* ✅ Simplified transaction handling
---
``bash`
npm install @nestlize/repositoryor
yarn add @nestlize/repositoryor
pnpm add @nestlize/repository
---
This package provides a reusable and extensible base repository class that works with sequelize-typescript. It reduces repetitive CRUD logic while keeping full flexibility for different entity needs.
---
| Feature | Description |
|-----------------------|--------------------------------------------------------------------|
| ✅ Abstract class | Extend AbstractRepository for each model |CreationAttributes
| ✅ Generic typing | Supports custom DTOs or defaults to Sequelize |paranoid
| ✅ Soft delete | Supports models with force option |repository.transaction()
| ✅ Transaction utility | for scoped logic |logger
| ✅ Logger injection | Optional NestJS logger for better traceability |
| ✅ Flexible options | Configure , autoGenerateId, etc. |
---
Configuration options for the abstract repository:
| Option | Type | Default | Description |
|------------------|--------------------------|-------------------------|-------------------------------------------------------|
| logger | Logger | NestJS default Logger | Optional NestJS logger instance for internal logging |
---
All methods return Promises.
| Method | Parameters | Description |
|------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------|
| create(dto, options?) | dto: CreationAttributes, options?: CreateOptions | Creates a new record | insert(dto, options?)
| | Same as create | Alias for create | insertMany(dtos, options?)
| | dtos: CreationAttributes, options?: BulkCreateOptions | Creates multiple records | findByPk(primaryKey, options?)
| | primaryKey: string \| number, options?: Omit | Find record by primary key | findOne(query?, options?)
| | query?: WhereOptions, options?: Omit | Find single record by query | findAll(query?, options?)
| | query?: WhereOptions, options?: Omit | Find all matching records | findAllPaginated(options?)
| | limit?: number, offset?: number, page?: number, query?: WhereOptions, options?: Omit | Find paginated records and total count |updateByPk(primaryKey, dto, options?)
| | primaryKey: string \| number, dto: Partial, options?: SaveOptions | Update record by primary key |deleteByPk(primaryKey, options?)
| | primaryKey: string \| number, options?: InstanceDestroyOptions | Delete (soft/hard) record by primary key |restoreByPk(primaryKey, options?)
| | primaryKey: string \| number, options?: InstanceRestoreOptions | Restore previously soft-deleted record |transaction(runInTransaction)
| | (transaction: Transaction) => Promise | Execute callback within a Sequelize transaction |calculateOffset(limit: number, page: number)
| | limit: number, page: number | Calculate offset for page pagination |
---
BaseModel extends from sequelize Model class adding timestamps
`ts
import { BaseModel } from '@nestlize/repository'
@Table({ tableName: 'users', paranoid: true })
export class User extends BaseModel
@PrimaryKey
@Default(DataType.UUIDV4)
@Column
user_id: string;
@Column
name: string;
@Column
email: string;
}
`
---
`ts
import { AbstractRepository } from '@nestlize/repository';
@Injectable()
export class UserRepository extends AbstractRepository
constructor(@InjectModel(User) userModel: typeof User) {
super(userModel);
}
}
`
---
`ts
@Injectable()
export class UserService {
constructor(private readonly users: UserRepository) {}
async createUser(dto: CreateUserDto) {
return this.users.create(dto);
}
async getUsers() {
return this.users.findAll();
}
async updateUser(id: string, update: YourUpdateType) {
return this.users.updateByPk(id, update);
}
}
`
---
You can pass options when instantiating:
`ts`
{
logger: new MyCustomLogger('MyRepo'), // optional
}
---
`ts`
await repo.transaction(async (transaction) => {
await repo.insert(data, { transaction });
await transaction.commit();
});
---
* Override methods like create() or updateByPk()` to apply custom hooks or validation.
* Extend with filters, scopes, or relations as needed.
---
MIT © Kiril Yakymchuk
---