@decaf-ts/db-decorators

中文文档
0.20.0发布于 2026/11/07MPL-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 2441

Agnostic database decorators and repository

原始使用文档
文档目录20 节
  1. DB-Decorators: Database Operations Made Simple
  2. Core Concepts
  3. DB-Decorators
  4. Repository
  5. Creating a Repository
  6. Operation Hooks
  7. Operation Decorators
  8. Context
  9. Additional Decorators
  10. @id
  11. @generated
  12. @hash
  13. @composed
  14. @version
  15. Related
  16. Social
  17. Getting help
  18. Contributing
  19. Supporting
  20. License

Banner

DB-Decorators: Database Operations Made Simple

The db-decorators library provides a comprehensive set of TypeScript decorators and utilities for database operations. It implements the repository pattern with support for model definition, validation, identity management, and operation hooks. The library enables developers to define database models with decorators, perform CRUD operations with validation, and customize behavior during database operations through operation hooks.

Release docs refreshed on 2025-11-26. See workdocs/reports/RELEASE_NOTES.md for ticket summaries.

Core Concepts

  • Repository: An abstract base class that implements the repository pattern, providing a consistent interface for CRUD operations.
  • Operation Hooks: The Repository class provides Prefix and Suffix methods for each CRUD operation, allowing you to execute custom logic before and after the main operation.
  • Operation Decorators: Decorators like @onCreate, @onUpdate, @onDelete, and @onRead allow you to attach custom logic to specific repository operations.
  • Context: A class for passing contextual information through the different layers of your application.
  • Database-related Decorators: A set of decorators for handling common database tasks, such as defining primary keys (@id), generating values (@generated), hashing values (@hash), composing values from other properties (@composed), and managing version numbers (@version).

Licence GitHub language count GitHub top language

Build & Test CodeQLSnyk Analysis Pages builder .github/workflows/release-on-tag.yaml

Open Issues Closed Issues Pull Requests Maintained

Forks Stars Watchers

Node Version NPM Version

Documentation available here

Minimal size: 9 KB kb gzipped

DB-Decorators

The db-decorators library is a powerful TypeScript framework for database operations that leverages decorators to simplify database interactions. It provides a comprehensive solution for implementing the repository pattern with built-in support for model definition, validation, identity management, and operation hooks.

Key Features

  1. Repository Pattern Implementation
  • Abstract BaseRepository class providing the foundation for CRUD operations
  • Concrete Repository class with validation support
  • Support for bulk operations through the BulkCrudOperator interface
  1. Model Management
  • Model definition with TypeScript decorators
  • Identity management with the @id() decorator
  • Property composition with @composed() and @composedFromKeys() decorators
  • Versioning support with the @version() decorator
  • Transient properties with the @transient() decorator
  1. Operation Hooks
  • Pre-operation hooks with @on(), @onCreate(), @onUpdate(), etc.
  • Post-operation hooks with @after(), @afterCreate(), @afterUpdate(), etc.
  • Custom operation handlers through the Operations registry
  1. Context Management
  • Hierarchical context chains with parent-child relationships
  • Context accumulation for state management
  • Operation-specific context creation
  1. Validation
  • Integration with decorator-validation library
  • Automatic validation during CRUD operations
  • Custom validation rules through decorators

The library is designed to be extensible and adaptable to different database backends, providing a consistent API regardless of the underlying storage mechanism.

How to Use

This guide provides examples of how to use the main features of the @decaf-ts/db-decorators library.

Repository

The Repository class is an abstract base class that implements the repository pattern.

Creating a Repository

To create a repository, you need to extend the Repository class and implement the abstract CRUD methods.

import { Repository, Model } from '@decaf-ts/db-decorators';
import { model, id, required } from '@decaf-ts/decorator-validation';

@model()
class User extends Model {
  @id()
  id: string;

  @required()
  name: string;
}

class UserRepository extends Repository<User, any> {
  constructor() {
    super(User);
  }

  async create(model: User): Promise<User> {
    // Implementation for creating a user
    return model;
  }

  async read(key: string): Promise<User> {
    // Implementation for reading a user
    return new User({ id: key, name: 'User' });
  }

  async update(model: User): Promise<User> {
    // Implementation for updating a user
    return model;
  }

  async delete(key: string): Promise<User> {
    // Implementation for deleting a user
    const model = await this.read(key);
    return model;
  }
}

Operation Hooks

The Repository class provides Prefix and Suffix methods for each CRUD operation, allowing you to execute custom logic before and after the main operation.

class UserRepository extends Repository<User, any> {
  // ...

  protected async createPrefix(model: User, ...args: any[]): Promise<[User, ...any[], any]> {
    console.log('Before creating user...');
    return [model, ...args];
  }

  protected async createSuffix(model: User, context: any): Promise<User> {
    console.log('After creating user...');
    return model;
  }
}

Operation Decorators

Decorators like @onCreate, @onUpdate, @onDelete, and @onRead allow you to attach custom logic to specific repository operations.

import { onCreate, onUpdate } from '@decaf-ts/db-decorators';

const logOnCreate = onCreate((context, data, key, model) => {
  console.log(`Creating model: ${model.constructor.name}`);
});

@model()
@logOnCreate
class Product extends Model {
  // ...
}

Context

The Context class is used for passing contextual information through the different layers of your application.

import { Context } from '@decaf-ts/db-decorators';

const context = new Context();
context.set('user', 'admin');

// You can then pass the context to repository methods
// userRepository.create(user, context);

Additional Decorators

@id

Marks a property as the primary key.

@model()
class Product extends Model {
  @id()
  productId: string;
}

@generated

Indicates that a property's value is generated by the database.

@model()
class Order extends Model {
  @id()
  @generated()
  orderId: number;
}

@hash

Automatically hashes a property's value.

@model()
class User extends Model {
  @hash()
  password!: string;
}

@composed

Composes a property's value from other properties.

@model()
class Person extends Model {
  @composed(['firstName', 'lastName'], ' ')
  fullName: string;

  firstName: string;
  lastName: string;
}

@version

Automatically manages a version number for optimistic locking.

@model()
class Account extends Model {
  @version()
  version: number;
}

decaf-ts decorator-validation reflection

Social

LinkedIn

Languages

TypeScript JavaScript NodeJS ShellScript

Getting help

If you have bug reports, questions or suggestions please create a new issue.

Contributing

I am grateful for any contributions made to this project. Please read this to get started.

Supporting

The first and easiest way you can support it is by Contributing. Even just finding a typo in the documentation is important.

Financial support is always welcome and helps keep both me and the project alive and healthy.

So if you can, if this project in any way. either by learning something or simply by helping you save precious time, please consider donating.

License

This project is released under the Mozilla Public License 2.0.

By developers, for developers...

版本与发布记录

@decaf-ts/db-decorators 共发布 137 个版本,首次发布于 2024/10/01;过去 12 个月发布了 71 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.20.0latest2026/11/076 天前
0.19.52026/09/201 个月前
0.19.42026/09/072 个月前
0.19.22026/09/032 个月前
0.19.12026/09/032 个月前
0.19.02026/09/012 个月前

关于 @decaf-ts/db-decorators 的常见问题

@decaf-ts/db-decorators 是什么?

Agnostic database decorators and repository

如何安装 @decaf-ts/db-decorators?

在项目目录运行 npm install @decaf-ts/db-decorators,或使用 pnpm add / yarn add / bun add。

@decaf-ts/db-decorators 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@decaf-ts/db-decorators 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@decaf-ts/db-decorators 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@decaf-ts/db-decorators 可以商用吗?

@decaf-ts/db-decorators 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@decaf-ts/db-decorators 的下载量有多少?

根据 npm 官方下载统计,@decaf-ts/db-decorators 在 2026/10/12 – 2026/11/10 这 30 天内被下载 2,441 次,日均约 81 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@decaf-ts/db-decorators 还在维护吗?

最新版本 0.20.0 发布于 2026/11/07(6 天前);至今共发布 137 个版本,其中过去 12 个月发布了 71 个;首次发布于 2024/10/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。