@lovrabet/sdk 1.2.8 → 1.3.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,65 @@
1
+ import type { HttpClient } from "../http/http-client";
2
+ /**
3
+ * BFF 客户端请求参数
4
+ */
5
+ export interface BffExecuteRequest {
6
+ /** 脚本名称(endpoint 函数名) */
7
+ scriptName: string;
8
+ /** 请求体参数(可选) */
9
+ params?: Record<string, any>;
10
+ /** Fetch 请求选项(可选) */
11
+ options?: RequestInit;
12
+ }
13
+ /**
14
+ * BFF 客户端 - 调用 Backend For Frontend 端点
15
+ *
16
+ * 与其他 SDK 接口保持一致的响应处理逻辑:
17
+ * - 成功:返回 data(业务数据)
18
+ * - 失败:抛出 LovrabetError 异常(由 processResponse 处理)
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * // 无参数调用
23
+ * const templates = await client.bff.execute({
24
+ * scriptName: 'getBundleTemplates'
25
+ * });
26
+ * templates.forEach(template => console.log(template.name));
27
+ *
28
+ * // 带参数调用
29
+ * const price = await client.bff.execute({
30
+ * scriptName: 'calculatePrice',
31
+ * params: { productId: '123', quantity: 10 }
32
+ * });
33
+ * console.log('Price:', price);
34
+ *
35
+ * // 带 Fetch 选项
36
+ * const result = await client.bff.execute({
37
+ * scriptName: 'getData',
38
+ * params: { id: '123' },
39
+ * options: { headers: { 'X-Custom-Header': 'value' } }
40
+ * });
41
+ *
42
+ * // 带类型提示
43
+ * interface BundleTemplate {
44
+ * id: string;
45
+ * name: string;
46
+ * items: string[];
47
+ * }
48
+ * const templates = await client.bff.execute<BundleTemplate>({
49
+ * scriptName: 'getBundleTemplates'
50
+ * });
51
+ * ```
52
+ */
53
+ export declare class BffClient {
54
+ private httpClient;
55
+ private appCode;
56
+ constructor(httpClient: HttpClient, appCode: string);
57
+ /**
58
+ * 调用 Backend For Frontend (BFF) 端点
59
+ *
60
+ * @param request 请求参数
61
+ * @returns BFF 函数返回的业务数据
62
+ * @throws {LovrabetError} 当 HTTP 请求失败时抛出异常
63
+ */
64
+ execute<T = any>(request: BffExecuteRequest): Promise<T>;
65
+ }
@@ -1,10 +1,4 @@
1
1
  import type { HttpClient } from "../http";
2
+ import type { User } from "./types";
2
3
  export declare function getUserList(httpClient: HttpClient): Promise<User[]>;
3
- export type User = {
4
- code: string;
5
- userName: string;
6
- nickName?: string | null;
7
- mobile: string;
8
- email?: string | null;
9
- avatar?: string | null;
10
- };
4
+ export type { User };
@@ -1,54 +1,97 @@
1
1
  import type { HttpClient } from "../http/http-client";
2
- import type { SqlExecuteResult } from "./types";
2
+ import { SqlClient } from "./sql-client";
3
+ import { BffClient } from "./bff-client";
4
+ import { UserClient } from "./user-client";
3
5
  /**
4
- * API 命名空间 - 管理通用 API 调用(SQL、Function 等)
6
+ * API 命名空间 - 别名入口
5
7
  *
6
- * 设计原则:
7
- * 1. 依赖注入 - 通过构造函数注入 HttpClient
8
- * 2. 类型安全 - 支持泛型,提供 TypeScript 类型推断
9
- * 3. 统一错误处理 - 成功返回数据,失败抛出 LovrabetError
10
- * 4. 风格一致 - 与 Model 的 getList/getOne 保持一致
8
+ * 推荐使用客户端方式:
9
+ * - SQL: `client.sql.execute()`
10
+ * - BFF: `client.bff.execute()`
11
+ * - User: `client.user.getList()`
12
+ *
13
+ * 此命名空间提供向后兼容的别名:
14
+ * - `client.api.sql()` → `client.sql.execute()`
15
+ * - `client.api.bff()` → `client.bff.execute()`
16
+ * - `client.api.getUserList()` → `client.user.getList()`
11
17
  */
12
18
  export declare class ApiNamespace {
13
19
  private httpClient;
14
- constructor(httpClient: HttpClient);
20
+ private appCode;
21
+ constructor(httpClient: HttpClient, appCode: string);
22
+ /**
23
+ * SQL 客户端实例
24
+ */
25
+ private _sql?;
15
26
  /**
16
- * 执行自定义 SQL 查询
27
+ * SQL 查询别名 - 推荐使用 `client.sql.execute()`
17
28
  *
18
- * @param sqlCode SQL代码(字符串格式 "appCode-sqlId" 或数字ID)
19
- * @param params SQL参数对象(可选)
20
- * @returns SQL执行结果(包含 execSuccess 和 execResult)
29
+ * @example
30
+ * ```typescript
31
+ * // 推荐用法(对象参数)
32
+ * const data = await client.sql.execute({
33
+ * sqlCode: 'fc8e7777-06e3847d',
34
+ * params: { userId: '123' }
35
+ * });
36
+ *
37
+ * // 别名用法(兼容)
38
+ * const data = await client.api.sql({
39
+ * sqlCode: 'fc8e7777-06e3847d',
40
+ * params: { userId: '123' }
41
+ * });
42
+ * ```
43
+ */
44
+ get sql(): SqlClient["execute"];
45
+ /**
46
+ * SQL 查询别名(旧名称)- 向后兼容
47
+ *
48
+ * @deprecated 使用 `client.sql.execute()` 或 `client.api.sql()`
49
+ */
50
+ get executeSql(): SqlClient["execute"];
51
+ /**
52
+ * BFF 客户端实例
53
+ */
54
+ private _bff?;
55
+ /**
56
+ * BFF 查询别名 - 推荐使用 `client.bff.execute()`
21
57
  *
22
58
  * @example
23
59
  * ```typescript
24
- * // 无参数查询
25
- * const data = await client.api.executeSql('fc8e7777-06e3847d');
26
- * if (data.execSuccess) {
27
- * const results = data.execResult;
28
- * results.forEach(item => console.log(item));
29
- * }
30
- *
31
- * // 参数化查询
32
- * const data = await client.api.executeSql('fc8e7777-xxxxx', {
33
- * userId: '123',
34
- * startDate: '2025-01-01'
60
+ * // 推荐用法(对象参数)
61
+ * const result = await client.bff.execute({
62
+ * scriptName: 'getBundleTemplates'
63
+ * });
64
+ *
65
+ * // 别名用法(兼容)
66
+ * const result = await client.api.bff({
67
+ * scriptName: 'getBundleTemplates'
35
68
  * });
69
+ * ```
70
+ */
71
+ get bff(): BffClient["execute"];
72
+ /**
73
+ * User 客户端实例
74
+ */
75
+ private _user?;
76
+ /**
77
+ * User 查询别名 - 推荐使用 `client.user.getList()`
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * // 推荐用法
82
+ * const userList = await client.user.getList();
36
83
  *
37
- * // 带类型提示
38
- * interface PageStat {
39
- * creation_date: string;
40
- * page_count: number;
41
- * }
42
- * const data = await client.api.executeSql<PageStat>('fc8e7777-06e3847d');
43
- * if (data.execSuccess && data.execResult) {
44
- * data.execResult.forEach(stat => {
45
- * console.log(stat.creation_date, stat.page_count);
46
- * });
47
- * }
84
+ * // 别名用法(兼容)
85
+ * const userList = await client.api.getUserList();
48
86
  * ```
49
87
  */
50
- executeSql<T = Record<string, any>>(sqlCode: string | number, params?: Record<string, string | number>): Promise<SqlExecuteResult<T>>;
51
- user: {
52
- getList: () => Promise<import("./get-user-list").User[]>;
88
+ get getUserList(): UserClient["getList"];
89
+ /**
90
+ * User 客户端别名 - 推荐使用 `client.user.getList()`
91
+ *
92
+ * @deprecated 使用 `client.user.getList()`
93
+ */
94
+ get user(): {
95
+ getList: UserClient["getList"];
53
96
  };
54
97
  }
@@ -0,0 +1,47 @@
1
+ import type { HttpClient } from "../http/http-client";
2
+ import type { SqlExecuteResult } from "./types";
3
+ /**
4
+ * SQL 客户端 - 执行自定义 SQL 查询
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * // 推荐:对象参数
9
+ * const data = await client.sql.execute({
10
+ * sqlCode: 'fc8e7777-06e3847d',
11
+ * params: { userId: '123', startDate: '2025-01-01' }
12
+ * });
13
+ *
14
+ * // 兼容:直接传参
15
+ * const data = await client.sql.execute('fc8e7777-06e3847d', {
16
+ * userId: '123',
17
+ * startDate: '2025-01-01'
18
+ * });
19
+ *
20
+ * // 带类型提示
21
+ * interface PageStat {
22
+ * creation_date: string;
23
+ * page_count: number;
24
+ * }
25
+ * const data = await client.sql.execute<PageStat>({
26
+ * sqlCode: 'fc8e7777-06e3847d'
27
+ * });
28
+ * ```
29
+ */
30
+ export declare class SqlClient {
31
+ private httpClient;
32
+ constructor(httpClient: HttpClient);
33
+ /**
34
+ * 执行自定义 SQL 查询
35
+ *
36
+ * 支持两种调用方式:
37
+ * 1. execute({ sqlCode, params }) - 对象参数(推荐)
38
+ * 2. execute(sqlCode, params) - 直接传参(兼容)
39
+ *
40
+ * @returns SQL执行结果(包含 execSuccess 和 execResult)
41
+ */
42
+ execute<T = Record<string, any>>(sqlCode: string | number, params?: Record<string, string | number>): Promise<SqlExecuteResult<T>>;
43
+ execute<T = Record<string, any>>(options: {
44
+ sqlCode: string | number;
45
+ params?: Record<string, string | number>;
46
+ }): Promise<SqlExecuteResult<T>>;
47
+ }
@@ -16,3 +16,20 @@ export interface SqlExecuteResult<T = Record<string, any>> {
16
16
  /** SQL 查询结果数组 */
17
17
  execResult?: T[];
18
18
  }
19
+ /**
20
+ * 用户信息
21
+ */
22
+ export interface User {
23
+ /** 用户代码 */
24
+ code: string;
25
+ /** 用户名 */
26
+ userName: string;
27
+ /** 昵称 */
28
+ nickName?: string | null;
29
+ /** 手机号 */
30
+ mobile: string;
31
+ /** 邮箱 */
32
+ email?: string | null;
33
+ /** 头像 */
34
+ avatar?: string | null;
35
+ }
@@ -0,0 +1,20 @@
1
+ import type { HttpClient } from "../http/http-client";
2
+ /**
3
+ * User 客户端 - 用户信息相关 API
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * const userList = await client.user.getList();
8
+ * console.log(userList);
9
+ * ```
10
+ */
11
+ export declare class UserClient {
12
+ private httpClient;
13
+ constructor(httpClient: HttpClient);
14
+ /**
15
+ * 获取用户列表
16
+ *
17
+ * @returns 用户列表数组
18
+ */
19
+ getList: () => Promise<import("./types").User[]>;
20
+ }
@@ -1,5 +1,8 @@
1
1
  import type { ClientConfig, LovrabetClient as ILovrabetClient, Environment, BaseModelMethods } from '../types';
2
2
  import { ApiNamespace } from '../api';
3
+ import { SqlClient } from '../api/sql-client';
4
+ import { BffClient } from '../api/bff-client';
5
+ import { UserClient } from '../api/user-client';
3
6
  /**
4
7
  * Lovrabet SDK 核心客户端类
5
8
  *
@@ -25,7 +28,24 @@ export declare class LovrabetClient implements ILovrabetClient {
25
28
  [modelName: string]: BaseModelMethods;
26
29
  };
27
30
  /**
28
- * API 命名空间 - 提供通用 API 调用(SQL、Function 等)
31
+ * SQL 客户端 - 执行自定义 SQL 查询
32
+ */
33
+ readonly sql: SqlClient;
34
+ /**
35
+ * BFF 客户端 - 调用 Backend For Frontend 端点
36
+ */
37
+ readonly bff: BffClient;
38
+ /**
39
+ * User 客户端 - 用户信息相关 API
40
+ */
41
+ readonly user: UserClient;
42
+ /**
43
+ * API 命名空间 - 别名入口(向后兼容)
44
+ *
45
+ * 推荐使用命名空间方式:
46
+ * - `client.sql.execute()` 而非 `client.api.sql()`
47
+ * - `client.bff.execute()` 而非 `client.api.bff()`
48
+ * - `client.user.getList()` 而非 `client.api.getUserList()`
29
49
  */
30
50
  readonly api: ApiNamespace;
31
51
  constructor(config: ClientConfig);
@@ -4,11 +4,13 @@ export declare class LovrabetError extends Error {
4
4
  readonly code?: string;
5
5
  readonly response?: any;
6
6
  readonly description?: ErrorDescription;
7
+ readonly cause?: unknown;
7
8
  constructor(message: string, options?: {
8
9
  status?: number;
9
10
  code?: string;
10
11
  response?: any;
11
12
  description?: ErrorDescription;
13
+ cause?: unknown;
12
14
  });
13
15
  toJSON(): {
14
16
  name: string;
@@ -17,6 +19,7 @@ export declare class LovrabetError extends Error {
17
19
  code: string;
18
20
  response: any;
19
21
  description: ErrorDescription;
22
+ cause: unknown;
20
23
  };
21
24
  }
22
25
  export declare function createErrorHandler(onError?: (error: any) => void): (error: any) => Promise<never>;
@@ -1,2 +1,6 @@
1
1
  export { LovrabetError, createErrorHandler } from "./errors";
2
2
  export { isBrowser, warnBrowserAccessKey } from './browser-detection';
3
+ export { safe } from './safe';
4
+ export type { SafeResult } from './safe';
5
+ export { sqlSafe } from './sql-safe';
6
+ export type { SqlSafeResult } from './sql-safe';
@@ -0,0 +1,54 @@
1
+ import { LovrabetError } from './errors';
2
+ /**
3
+ * 安全执行结果类型
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * const { data, error } = await safe(client.models.customer.filter({ ... }));
8
+ * if (error) {
9
+ * console.error(error.message, error.description);
10
+ * return;
11
+ * }
12
+ * // 使用 data
13
+ * ```
14
+ */
15
+ export interface SafeResult<T> {
16
+ /** 成功时的数据,失败时为 null */
17
+ data: T | null;
18
+ /** 失败时的错误对象,成功时为 null */
19
+ error: LovrabetError | null;
20
+ }
21
+ /**
22
+ * Promise 或返回 Promise 的函数类型
23
+ */
24
+ type PromiseLike<T> = Promise<T> | (() => Promise<T>);
25
+ /**
26
+ * 安全执行 Promise,将异常转换为返回值
27
+ *
28
+ * @param fn - Promise 或返回 Promise 的函数
29
+ * @returns 包含 data 和 error 的结果对象
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * // 直接传入 Promise
34
+ * const { data, error } = await safe(client.models.customer.filter({ where: { status: 'active' } }));
35
+ * if (error) {
36
+ * console.error(error.message);
37
+ * return;
38
+ * }
39
+ * console.log(data);
40
+ *
41
+ * // 传入函数(延迟执行)
42
+ * const { data, error } = await safe(() => client.models.customer.filter({ ... }));
43
+ *
44
+ * // 旧代码继续工作(抛异常模式)
45
+ * try {
46
+ * const data = await client.models.customer.filter({ ... });
47
+ * console.log(data);
48
+ * } catch (error) {
49
+ * console.error(error);
50
+ * }
51
+ * ```
52
+ */
53
+ export declare function safe<T>(fn: PromiseLike<T>): Promise<SafeResult<T>>;
54
+ export {};
@@ -0,0 +1,78 @@
1
+ import { LovrabetError } from './errors';
2
+ import type { SqlExecuteResult } from '../api/types';
3
+ /**
4
+ * sqlSafe 执行结果类型
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * const { data, error } = await sqlSafe(() => client.sql.execute(...));
9
+ * if (error) {
10
+ * console.error(error.message, error.code, error.cause);
11
+ * return;
12
+ * }
13
+ * // data 直接是查询结果数组
14
+ * data.forEach(row => console.log(row));
15
+ * ```
16
+ */
17
+ export interface SqlSafeResult<T> {
18
+ /** 成功时的查询结果数组,失败时为 null */
19
+ data: T[] | null;
20
+ /** 失败时的错误对象,成功时为 null */
21
+ error: LovrabetError | null;
22
+ }
23
+ /**
24
+ * Promise 或返回 Promise 的函数类型
25
+ */
26
+ type SqlPromiseLike<T> = Promise<SqlExecuteResult<T>> | (() => Promise<SqlExecuteResult<T>>);
27
+ /**
28
+ * 安全执行 SQL 查询,统一处理 HTTP 错误和业务逻辑错误
29
+ *
30
+ * @param fn - 返回 SqlExecuteResult 的 Promise 或函数
31
+ * @returns 包含 data(查询结果数组)和 error 的结果对象
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * // 基础用法
36
+ * const { data, error } = await sqlSafe(() =>
37
+ * client.sql.execute({ sqlCode: 'fc8e7777-06e3847d' })
38
+ * );
39
+ *
40
+ * if (error) {
41
+ * console.error('查询失败:', error.message);
42
+ * return;
43
+ * }
44
+ *
45
+ * // data 直接是查询结果数组
46
+ * console.log(`查询到 ${data.length} 条记录`);
47
+ * data.forEach(row => console.log(row));
48
+ *
49
+ * // 带类型提示
50
+ * interface UserStat {
51
+ * id: number;
52
+ * name: string;
53
+ * login_count: number;
54
+ * }
55
+ *
56
+ * const { data, error } = await sqlSafe<UserStat>(() =>
57
+ * client.sql.execute({ sqlCode: 'user-stats' })
58
+ * );
59
+ *
60
+ * if (error) {
61
+ * if (error.code === 'SQL_ERROR') {
62
+ * // 业务逻辑失败(execSuccess = false)
63
+ * console.error('SQL 执行失败:', error.cause);
64
+ * } else {
65
+ * // HTTP 错误(404、500 等)
66
+ * console.error('请求失败:', error.status, error.message);
67
+ * }
68
+ * return;
69
+ * }
70
+ *
71
+ * // data 是 UserStat[]
72
+ * data.forEach(stat => {
73
+ * console.log(`${stat.name}: ${stat.login_count} 次登录`);
74
+ * });
75
+ * ```
76
+ */
77
+ export declare function sqlSafe<T>(fn: SqlPromiseLike<T>): Promise<SqlSafeResult<T>>;
78
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovrabet/sdk",
3
- "version": "1.2.8",
3
+ "version": "1.3.0-beta.1",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",