npm package: @pixmason/nest-cloudbase-sdk
Description: NestJS CloudBase module with dynamic initialization and CRUD helpers
Author: PixMason
Latest version: 0.1.0

# @pixmason/nest-cloudbase-sdk

一个面向 NestJS 的 CloudBase SDK 封装模块，支持动态配置注入（`forRoot` / `forRootAsync`）、基础 CRUD、批量操作、聚合查询、存在性判断与 Repository 模式。

## 特性

- 支持 Nest 动态模块：`CloudbaseModule.forRoot`、`CloudbaseModule.forRootAsync`
- 统一数据能力：`findOne/createData/updateData/removeData`
- 批量能力：`findMany/updateMany/removeMany/updateByIds`
- 统计与存在性：`countTotal/isExistData/findExistData/findExistIds`
- 高级聚合：`findManyByPipeline`
- Repository 模式：按集合创建仓储，减少重复传参
- 中文错误提示 + 错误码，便于全局异常拦截

## 安装

### npm

```bash
npm i @pixmason/nest-cloudbase-sdk
```

### pnpm

```bash
pnpm add @pixmason/nest-cloudbase-sdk
```

### yarn

```bash
yarn add @pixmason/nest-cloudbase-sdk
```

## 快速开始

### 1) 在 AppModule 注册（同步配置）

```ts
import { Module } from '@nestjs/common'
import { CloudbaseModule } from '@pixmason/nest-cloudbase-sdk'

@Module({
	imports: [
		CloudbaseModule.forRoot({
			env: '你的环境ID',
			secretId: '你的SecretId',
			secretKey: '你的SecretKey',
			batchLimit: 100, // 可选，默认 100
		}),
	],
})
export class AppModule {}
```

### 2) 在服务中注入并调用

```ts
import { Injectable } from '@nestjs/common'
import { CloudbaseService } from '@pixmason/nest-cloudbase-sdk'

@Injectable()
export class UserService {
	constructor(private readonly cloudbaseService: CloudbaseService) {}

	async getUserList() {
		return this.cloudbaseService.findMany('users', {
			currentPage: 1,
			pageSize: 20,
			where: { status: 'active' },
			sort: { _id: -1 },
			withTotal: true, // 默认就是 true
		})
	}
}
```

## 支持的调用方式

### 模块初始化

- `CloudbaseModule.forRoot(options)`
- `CloudbaseModule.forRootAsync({ imports, inject, useFactory })`

### CloudbaseService 方法

- `findOne(collection, where)`
- `createData(collection, data)`（支持单条和批量）
- `updateData(collection, where, data)`
- `removeData(collection, where)`
- `findMany(collection, params)`
- `findManyByPipeline(collection, pipeline)`
- `updateMany(collection, where, data)`
- `updateByIds(collection, items)`
- `removeMany(collection, where)`
- `countTotal(collection, where?)`
- `findExistData(collection, ids, field?)`
- `isExistData(collection, ids, options?)`
- `findExistIds(collection, ids)`
- `repository(collection)`

### Repository 调用方式

```ts
const userRepo = cloudbaseService.repository<{ _id: string; name: string }>('users')

await userRepo.findOne({ _id: 'xxx' })
await userRepo.findMany({ currentPage: 1, pageSize: 10 })
await userRepo.createData({ name: 'Tom' })
await userRepo.isExistData(['id1', 'id2'], { allMustExist: true })
```

## 完整接入示例（forRootAsync）

### 1) AppModule

```ts
import { Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { CloudbaseModule } from '@pixmason/nest-cloudbase-sdk'

@Module({
	imports: [
		ConfigModule.forRoot({ isGlobal: true }),
		CloudbaseModule.forRootAsync({
			imports: [ConfigModule],
			inject: [ConfigService],
			useFactory: (configService: ConfigService) => ({
				env: configService.get<string>('ENV_ID'),
				secretId: configService.get<string>('SECRET_ID'),
				secretKey: configService.get<string>('SECRET_KEY'),
				batchLimit: Number(configService.get<string>('BATCH_LIMIT') ?? 100),
			}),
		}),
	],
})
export class AppModule {}
```

### 2) 业务 Service

```ts
import { Injectable } from '@nestjs/common'
import { CloudbaseService } from '@pixmason/nest-cloudbase-sdk'

@Injectable()
export class DemoService {
	constructor(private readonly cloudbaseService: CloudbaseService) {}

	async demo(collection: string) {
		const created = await this.cloudbaseService.createData(collection, [{ name: 'A' }, { name: 'B' }])

		const page = await this.cloudbaseService.findMany(collection, {
			currentPage: 1,
			pageSize: 20,
			where: {},
			sort: { _id: 1 },
		})

		const existAny = await this.cloudbaseService.isExistData(collection, created.ids)
		const existAll = await this.cloudbaseService.isExistData(collection, created.ids, {
			allMustExist: true,
		})

		return {
			created,
			page,
			existAny,
			existAll,
		}
	}
}
```

## 常用返回结构

### findMany

```ts
{
  data: T[];
  currentPage: number;
  pageSize: number;
  total?: number;
}
```

- 默认 `withTotal = true`

### createData

```ts
{
  id?: string;   // 单条创建时返回
  ids: string[]; // 单条/批量统一返回
  total: number; // 创建成功条数
}
```

## isExistData 说明

`isExistData(collection, ids, { allMustExist })`

- `allMustExist = false`（默认）：存在任意一条即返回 `true`
- `allMustExist = true`：只有全部存在才返回 `true`

## 错误处理

SDK 抛出的错误类型为 `CloudbaseSdkError`，可通过 `code` 统一处理：

- `CLOUDBASE_INIT_FAILED`：初始化失败
- `CLOUDBASE_QUERY_FAILED`：查询/写入等数据库操作失败
- `CLOUDBASE_INVALID_PARAM`：参数不合法

示例：

```ts
try {
	await cloudbaseService.findMany('users', { currentPage: 1, pageSize: 10 })
} catch (error) {
	if (error instanceof CloudbaseSdkError) {
		console.log(error.code, error.message)
	}
}
```

## 配置项说明

`CloudbaseModuleOptions`：

- `env?: string`
- `accessKey?: string`
- `secretId?: string`
- `secretKey?: string`
- `sessionToken?: string`
- `context?: unknown`
- `timeout?: number`
- `proxy?: string`
- `version?: string`
- `batchLimit?: number`（可选，默认 100）