npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@chenpeiyuan/idb-repository

v1.0.1

Published

一个基于 Dexie.js 的 IndexedDB 仓库管理库,提供了简洁的 CRUD 操作接口。

Readme

@chenpeiyuan/idb-repository

一个基于 Dexie.js 的 IndexedDB 仓库管理库,提供了简洁的 CRUD 操作接口。

安装

npm install @chenpeiyuan/idb-repository

基本使用

1. 定义实体接口

import type { BaseEntity, OnlyCreateEntity } from '@chenpeiyuan/idb-repository';

// 可读写实体(支持添加、更新、删除)
export interface Product extends BaseEntity<number> {
  name: string;
  price: number;
  description?: string;
}

// 只创建实体(支持添加、删除,但不支持更新)
export interface Log extends OnlyCreateEntity<number> {
  level: 'info' | 'warn' | 'error';
  message: string;
  details?: any;
}

// 使用自定义ID类型的实体
export interface User extends BaseEntity<string> {
  username: string;
  email: string;
}

2. 创建数据库类

import Dexie from 'dexie';
import { Database, type InsertType, type IdGenerator, type Table } from '@chenpeiyuan/idb-repository';
import type { Product, Log, User } from './types';

// 自定义ID生成器(可选)
const stringIdGenerator: IdGenerator<string> = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 数字ID生成器(可选)
const numberIdGenerator: IdGenerator<number> = () => {
  return Date.now();
};

export class AppDatabase extends Database<number> {
  readonly products!: Table<Product>;
  readonly logs!: Table<Log>;

  constructor() {
    // 传入自定义ID生成器(可选)
    super('appDatabase', numberIdGenerator);
    
    this.version(1).stores({
      products: '++id, name, price, createdAt, updatedAt, version',
      logs: '++id, level, createdAt'
    });

    // 初始化钩子(可选)
    this.initAlterHooks(['products']); // 为可更新的表添加钩子
    this.initWriteHooks(['logs']);     // 为只创建的表添加钩子
  }
}

// 使用字符串ID的数据库
export class UserDatabase extends Database<string> {
  readonly users!: Table<User>;

  constructor() {
    super('userDatabase', stringIdGenerator);
    
    this.version(1).stores({
      users: 'id, username, email, createdAt, updatedAt, version'
    });

    this.initAlterHooks(['users']);
  }
}

3. 创建仓库实例

import { BaseRepository, OnlyCreateRepository } from '@chenpeiyuan/idb-repository';
import { AppDatabase, UserDatabase } from './database';

// 创建数据库实例
const db = new AppDatabase();
const userDb = new UserDatabase();

// 创建仓库实例
const productRepository = new BaseRepository<number, Product>(db.products);
const logRepository = new OnlyCreateRepository<number, Log>(db.logs);
const userRepository = new BaseRepository<string, User>(userDb.users);

4. 使用仓库操作数据

BaseRepository(可读写仓库)

// 添加产品
const productId = await productRepository.add({ name: 'iPhone 14', price: 6999 });

// 获取产品
const product = await productRepository.get(productId);

// 更新产品
if (product) {
  const updatedProduct = { ...product, price: 7999 };
  await productRepository.alt(updatedProduct);
}

// 删除产品
await productRepository.del(productId);

// 批量添加产品
const productIds = await productRepository.batchAdd([
  { name: 'iPhone 14', price: 6999 },
  { name: 'iPhone 14 Pro', price: 8999 }
]);

// 批量更新产品
const productsToUpdate = await Promise.all([
  productRepository.get(productIds[0]),
  productRepository.get(productIds[1])
]);

if (productsToUpdate[0] && productsToUpdate[1]) {
  const updatedProducts = [
    { ...productsToUpdate[0], price: 7499 },
    { ...productsToUpdate[1], price: 9499 }
  ];
  await productRepository.batchAlt(updatedProducts);
}

// 批量删除产品
await productRepository.batchDel(productIds);

// 获取所有产品
const allProducts = await productRepository.list();

// 使用字符串ID的用户操作
const userId = await userRepository.add({ username: 'admin', email: '[email protected]' });
const user = await userRepository.get(userId);

OnlyCreateRepository(只创建仓库)

// 添加日志
const logId = await logRepository.add({ level: 'info', message: '用户登录' });

// 获取日志
const log = await logRepository.get(logId);

// 删除日志
await logRepository.del(logId);

// 批量添加日志
await logRepository.batchAdd([
  { level: 'info', message: '用户登录' },
  { level: 'error', message: '登录失败' }
]);

// 批量删除日志
const logIds = [1, 2, 3];
await logRepository.batchDel(logIds);

// 获取所有日志
const allLogs = await logRepository.list();

API 文档

BaseRepository<K, T>

| 方法 | 描述 | 参数 | 返回值 | |------|------|------|--------| | add | 添加实体 | entity: InsertType<T> | Promise<K> | | del | 删除实体 | id: K | Promise<void> | | alt | 更新实体 | entity: T | Promise<void> | | get | 获取实体 | id: K | Promise<T | undefined> | | batchAdd | 批量添加实体 | entities: Array<InsertType<T>> | Promise<K[]> | | batchAlt | 批量更新实体 | entities: Array<T> | Promise<void> | | batchDel | 批量删除实体 | ids: Array<K> | Promise<void> | | list | 获取所有实体 | 无 | Promise<T[]> |

OnlyCreateRepository<K, T>

| 方法 | 描述 | 参数 | 返回值 | |------|------|------|--------| | add | 添加实体 | entity: InsertType<T> | Promise<K> | | del | 删除实体 | id: K | Promise<void> | | get | 获取实体 | id: K | Promise<T | undefined> | | batchAdd | 批量添加实体 | entities: Array<InsertType<T>> | Promise<K[]> | | batchDel | 批量删除实体 | ids: Array<K> | Promise<void> | | list | 获取所有实体 | 无 | Promise<T[]> |

类型定义

BaseEntity

type BaseEntity<K> = {
  id: K;
  createdAt: Date;
  updatedAt: Date;
  version: number;
};

OnlyCreateEntity

type OnlyCreateEntity<K> = {
  id: K;
  createdAt: Date;
};

InsertType

用于创建实体时的类型,自动排除了系统生成的字段。

WritableEntity

type WritableEntity<K> = {
  id: K;
  createdAt: Date;
};

ModifableEntry

type ModifableEntry = {
  updatedAt: Date;
  version: number;
};

IdGenerator

type IdGenerator<K> = () => K;

测试

运行测试:

npm test

许可证

MIT