rxtutils 1.1.2-beta.2 → 1.1.2-beta.21

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.
Files changed (56) hide show
  1. package/README.md +144 -1
  2. package/{dist/cjs → cjs}/cache/index.cjs +28 -15
  3. package/{dist/types → cjs}/cache/index.d.ts +13 -7
  4. package/cjs/request/index.cjs +150 -0
  5. package/{dist/types → cjs}/request/index.d.ts +12 -8
  6. package/cjs/store/index.cjs +10 -0
  7. package/cjs/store/index.d.ts +2 -0
  8. package/cjs/validator/decorators.cjs +246 -0
  9. package/cjs/validator/decorators.d.ts +159 -0
  10. package/cjs/validator/index.cjs +19 -0
  11. package/cjs/validator/index.d.ts +2 -0
  12. package/{dist/cjs → cjs}/validator/validator.cjs +78 -13
  13. package/cjs/validator/validator.d.ts +84 -0
  14. package/es/cache/index.d.ts +141 -0
  15. package/{dist/es → es}/cache/index.mjs +28 -15
  16. package/es/cache/indexDB.d.ts +52 -0
  17. package/es/index.d.ts +7 -0
  18. package/es/request/error.d.ts +31 -0
  19. package/es/request/index.d.ts +140 -0
  20. package/es/request/index.mjs +148 -0
  21. package/es/store/createGetter/index.d.ts +30 -0
  22. package/es/store/createStateStore/index.d.ts +42 -0
  23. package/es/store/index.d.ts +2 -0
  24. package/es/store/index.mjs +2 -0
  25. package/es/validator/decorators.d.ts +159 -0
  26. package/es/validator/decorators.mjs +234 -0
  27. package/es/validator/index.d.ts +2 -0
  28. package/es/validator/index.mjs +2 -0
  29. package/es/validator/validator.d.ts +84 -0
  30. package/{dist/es → es}/validator/validator.mjs +78 -13
  31. package/package.json +12 -9
  32. package/dist/cjs/request/index.cjs +0 -129
  33. package/dist/cjs/validator/decorators.cjs +0 -104
  34. package/dist/es/request/index.mjs +0 -127
  35. package/dist/es/validator/decorators.mjs +0 -92
  36. package/dist/types/validator/decorators.d.ts +0 -15
  37. package/dist/types/validator/validator.d.ts +0 -24
  38. /package/{dist/cjs → cjs/_utils}/defaultEquals.cjs +0 -0
  39. /package/{dist/cjs → cjs}/cache/indexDB.cjs +0 -0
  40. /package/{dist/types → cjs}/cache/indexDB.d.ts +0 -0
  41. /package/{dist/cjs → cjs}/index.cjs +0 -0
  42. /package/{dist/types → cjs}/index.d.ts +0 -0
  43. /package/{dist/cjs → cjs}/request/defaultHandlers.cjs +0 -0
  44. /package/{dist/cjs → cjs}/request/error.cjs +0 -0
  45. /package/{dist/types → cjs}/request/error.d.ts +0 -0
  46. /package/{dist/cjs → cjs}/store/createGetter/index.cjs +0 -0
  47. /package/{dist/types → cjs}/store/createGetter/index.d.ts +0 -0
  48. /package/{dist/cjs → cjs}/store/createStateStore/index.cjs +0 -0
  49. /package/{dist/types → cjs}/store/createStateStore/index.d.ts +0 -0
  50. /package/{dist/es → es/_utils}/defaultEquals.mjs +0 -0
  51. /package/{dist/es → es}/cache/indexDB.mjs +0 -0
  52. /package/{dist/es → es}/index.mjs +0 -0
  53. /package/{dist/es → es}/request/defaultHandlers.mjs +0 -0
  54. /package/{dist/es → es}/request/error.mjs +0 -0
  55. /package/{dist/es → es}/store/createGetter/index.mjs +0 -0
  56. /package/{dist/es → es}/store/createStateStore/index.mjs +0 -0
@@ -0,0 +1,141 @@
1
+ import { IndexedDBStorage } from './indexDB.js';
2
+
3
+ /**
4
+ * 缓存存储类型
5
+ * - sessionStorage: 会话存储,浏览器关闭后清除
6
+ * - localStorage: 本地存储,永久保存
7
+ * - indexedDB: IndexedDB 数据库存储
8
+ */
9
+ type StorageType = "sessionStorage" | "localStorage" | "indexedDB";
10
+ /**
11
+ * 缓存项接口定义
12
+ * 定义了单个缓存项的数据结构
13
+ *
14
+ * @template Param 缓存参数类型
15
+ * @template Data 缓存数据类型
16
+ */
17
+ interface ICache<Param, Data> {
18
+ /**
19
+ * 缓存的参数
20
+ * 用于标识和查找缓存项
21
+ */
22
+ params: Param;
23
+ /**
24
+ * 缓存的数据
25
+ * 实际存储的内容
26
+ */
27
+ data: Data;
28
+ /**
29
+ * 过期时间
30
+ * - ISO 8601 格式的字符串
31
+ * - 由 moment().add(cacheTime, 'seconds').toJSON() 生成
32
+ * - 示例:'2025-06-12T10:30:00.000Z'
33
+ */
34
+ expireTime: string;
35
+ }
36
+ /**
37
+ * 缓存选项接口
38
+ * @template Param 缓存参数类型
39
+ */
40
+ interface ICacheOptions<Param> {
41
+ /**
42
+ * 存储类型
43
+ * - 'sessionStorage': 会话存储,浏览器关闭后清除
44
+ * - 'localStorage': 本地存储,永久保存
45
+ * - 'indexedDB': IndexedDB 数据库存储
46
+ * - undefined: 仅在内存中缓存(默认值)
47
+ */
48
+ storageType?: StorageType;
49
+ /**
50
+ * 缓存键名
51
+ * - 当使用 localStorage/sessionStorage 时必须提供
52
+ * - 用于在存储中标识不同的缓存数据
53
+ * @default undefined 不使用持久化存储
54
+ */
55
+ cacheKey?: string;
56
+ /**
57
+ * 缓存时间(秒)
58
+ * - 超过这个时间的缓存项会被自动清除
59
+ * @default 60 一分钟
60
+ */
61
+ cacheTime?: number;
62
+ /**
63
+ * 缓存键比较函数
64
+ * - 用于判断两个缓存参数是否相等
65
+ * - 相等则认为是同一个缓存项
66
+ * @param prev 前一个参数
67
+ * @param next 后一个参数
68
+ * @returns 是否相等
69
+ * @default defaultEquals 使用 JSON.stringify 进行比较
70
+ */
71
+ cacheKeyEquals: (prev: Param, next: Param) => boolean;
72
+ /**
73
+ * IndexedDB 数据库名称
74
+ * - 仅在 storageType 为 'indexedDB' 时使用
75
+ * @default '__apiCacheDatabase__'
76
+ */
77
+ indexDBName?: string;
78
+ }
79
+ /** 存储类型映射表 */
80
+ declare const StorageMap: Record<StorageType | string, Storage>;
81
+ /**
82
+ * 缓存类
83
+ * @template Param 缓存参数类型
84
+ * @template Data 缓存数据类型
85
+ */
86
+ declare class Cache<Param, Data> {
87
+ /** 内存中的缓存数组 */
88
+ cache: ICache<Param, Data>[];
89
+ /** 缓存选项 */
90
+ private cacheOptions;
91
+ /** 存储实例 */
92
+ storage?: Storage | IndexedDBStorage;
93
+ /**
94
+ * 构造函数
95
+ * @param cacheType 存储类型
96
+ * @param cacheKey 缓存键名
97
+ * @param cacheTime 缓存时间(秒)
98
+ * @param indexDBName IndexedDB 数据库名称,默认值为 '__apiCacheDatabase__'
99
+ * @param cacheKeyEquals 缓存键比较函数,默认使用 defaultEquals
100
+ */
101
+ constructor(cacheType?: StorageType, cacheKey?: string, cacheTime?: number, indexDBName?: string, cacheKeyEquals?: (prev: Param, next: Param) => boolean);
102
+ /**
103
+ * 初始化缓存
104
+ * 从存储中加载已保存的缓存数据,并进行解析和过期处理
105
+ * @private
106
+ */
107
+ private _init;
108
+ /**
109
+ * 过滤掉已过期的缓存项
110
+ * 通过比较当前时间和过期时间,移除过期的缓存项
111
+ * @private
112
+ */
113
+ private _filterExpired;
114
+ /**
115
+ * 将当前缓存数据保存到存储中
116
+ * 如果设置了缓存键名且存储实例存在,则将缓存数据序列化后保存
117
+ * @private
118
+ */
119
+ private _saveToStorage;
120
+ /**
121
+ * 设置缓存数据
122
+ * @param params 缓存的参数
123
+ * @param data 要缓存的数据
124
+ * @param cacheOptions 可选的缓存配置,可以覆盖默认的缓存时间
125
+ */
126
+ setCache(params: Param, data: Data, cacheOptions?: Omit<ICacheOptions<Param>, "storageType" | "cacheKey" | "cacheKeyEquals">): void;
127
+ /**
128
+ * 获取缓存数据
129
+ * @param params 查询参数
130
+ * @returns 如果找到有效的缓存数据则返回数据,否则返回 null
131
+ */
132
+ getCache(params: Param): Data;
133
+ /**
134
+ * 清空所有缓存数据
135
+ * 清空内存中的缓存数组并同步到存储中
136
+ */
137
+ clear(): void;
138
+ }
139
+
140
+ export { StorageMap, Cache as default };
141
+ export type { ICache, ICacheOptions, StorageType };
@@ -1,7 +1,7 @@
1
1
  import { __awaiter, __generator, __assign } from 'tslib';
2
2
  import moment from 'moment';
3
3
  import { IndexedDBStorage } from './indexDB.mjs';
4
- import defaultEquals from '../defaultEquals.mjs';
4
+ import defaultEquals from '../_utils/defaultEquals.mjs';
5
5
 
6
6
  /** 存储类型映射表 */
7
7
  var StorageMap = {
@@ -14,8 +14,16 @@ var StorageMap = {
14
14
  * @template Data 缓存数据类型
15
15
  */
16
16
  var Cache = /** @class */ (function () {
17
+ /**
18
+ * 构造函数
19
+ * @param cacheType 存储类型
20
+ * @param cacheKey 缓存键名
21
+ * @param cacheTime 缓存时间(秒)
22
+ * @param indexDBName IndexedDB 数据库名称,默认值为 '__apiCacheDatabase__'
23
+ * @param cacheKeyEquals 缓存键比较函数,默认使用 defaultEquals
24
+ */
17
25
  function Cache(cacheType, cacheKey, cacheTime, indexDBName, cacheKeyEquals) {
18
- if (indexDBName === void 0) { indexDBName = '__apiCacheDatabase__'; }
26
+ if (indexDBName === void 0) { indexDBName = "__apiCacheDatabase__"; }
19
27
  if (cacheKeyEquals === void 0) { cacheKeyEquals = defaultEquals; }
20
28
  /** 内存中的缓存数组 */
21
29
  this.cache = [];
@@ -26,10 +34,10 @@ var Cache = /** @class */ (function () {
26
34
  indexDBName: indexDBName,
27
35
  cacheKeyEquals: cacheKeyEquals,
28
36
  };
29
- if (cacheType === 'indexedDB') {
30
- this.storage = new IndexedDBStorage(indexDBName, 'cacheStore');
37
+ if (cacheType === "indexedDB") {
38
+ this.storage = new IndexedDBStorage(indexDBName, "cacheStore");
31
39
  }
32
- else if (typeof cacheType === 'string') {
40
+ else if (typeof cacheType === "string") {
33
41
  this.storage = StorageMap[cacheType];
34
42
  }
35
43
  this._init();
@@ -51,15 +59,15 @@ var Cache = /** @class */ (function () {
51
59
  _d = (_c = JSON).parse;
52
60
  return [4 /*yield*/, this.storage.getItem(cacheKey)];
53
61
  case 1:
54
- _b.cache = _d.apply(_c, [(_e.sent()) || '[]']);
62
+ _b.cache = _d.apply(_c, [(_e.sent()) || "[]"]);
55
63
  return [3 /*break*/, 3];
56
64
  case 2:
57
65
  if (this.storage instanceof Storage) {
58
66
  this.storage = StorageMap[cacheType];
59
67
  if (this.storage) {
60
- if (typeof cacheKey === 'string') {
68
+ if (typeof cacheKey === "string") {
61
69
  try {
62
- this.cache = JSON.parse(this.storage.getItem(cacheKey) || '[]');
70
+ this.cache = JSON.parse(this.storage.getItem(cacheKey) || "[]");
63
71
  }
64
72
  catch (e) {
65
73
  this.cache = [];
@@ -76,7 +84,8 @@ var Cache = /** @class */ (function () {
76
84
  }
77
85
  });
78
86
  });
79
- }; /**
87
+ };
88
+ /**
80
89
  * 过滤掉已过期的缓存项
81
90
  * 通过比较当前时间和过期时间,移除过期的缓存项
82
91
  * @private
@@ -86,18 +95,20 @@ var Cache = /** @class */ (function () {
86
95
  return moment(item.expireTime).isAfter(moment());
87
96
  });
88
97
  this.cache = newCache;
89
- }; /**
98
+ };
99
+ /**
90
100
  * 将当前缓存数据保存到存储中
91
101
  * 如果设置了缓存键名且存储实例存在,则将缓存数据序列化后保存
92
102
  * @private
93
103
  */
94
104
  Cache.prototype._saveToStorage = function () {
95
105
  if (this.storage) {
96
- if (typeof this.cacheOptions.cacheKey === 'string') {
106
+ if (typeof this.cacheOptions.cacheKey === "string") {
97
107
  this.storage.setItem(this.cacheOptions.cacheKey, JSON.stringify(this.cache));
98
108
  }
99
109
  }
100
- }; /**
110
+ };
111
+ /**
101
112
  * 设置缓存数据
102
113
  * @param params 缓存的参数
103
114
  * @param data 要缓存的数据
@@ -114,10 +125,11 @@ var Cache = /** @class */ (function () {
114
125
  this.cache.push({
115
126
  params: params,
116
127
  data: data,
117
- expireTime: moment().add(cacheTime, 'seconds').toJSON(),
128
+ expireTime: moment().add(cacheTime, "seconds").toJSON(),
118
129
  });
119
130
  this._saveToStorage();
120
- }; /**
131
+ };
132
+ /**
121
133
  * 获取缓存数据
122
134
  * @param params 查询参数
123
135
  * @returns 如果找到有效的缓存数据则返回数据,否则返回 null
@@ -138,7 +150,8 @@ var Cache = /** @class */ (function () {
138
150
  }
139
151
  }
140
152
  return null;
141
- }; /**
153
+ };
154
+ /**
142
155
  * 清空所有缓存数据
143
156
  * 清空内存中的缓存数组并同步到存储中
144
157
  */
@@ -0,0 +1,52 @@
1
+ /**
2
+ * IndexedDB 存储类
3
+ * 提供了对 IndexedDB 数据库操作的简单封装
4
+ */
5
+ declare class IndexedDBStorage {
6
+ /** 数据库名称 */
7
+ private dbName;
8
+ /** 存储对象名称 */
9
+ private storeName;
10
+ /** 数据库连接实例 */
11
+ private db;
12
+ /**
13
+ * 构造函数
14
+ * @param dbName 数据库名称
15
+ * @param storeName 存储对象名称
16
+ */
17
+ constructor(dbName: string, storeName: string);
18
+ /**
19
+ * 打开数据库连接
20
+ * 如果数据库不存在则创建新的数据库和存储对象
21
+ * @private
22
+ * @returns Promise<IDBDatabase> 数据库连接实例
23
+ */
24
+ private _open;
25
+ /**
26
+ * 获取存储对象
27
+ * @param mode 事务模式,默认为只读模式
28
+ * - readonly: 只读模式
29
+ * - readwrite: 读写模式
30
+ * @private
31
+ * @returns Promise<IDBObjectStore> 存储对象实例
32
+ */
33
+ private _getStore;
34
+ /**
35
+ * 设置键值对
36
+ * @param key 键名
37
+ * @param value 要存储的值
38
+ * @returns Promise<void> 存储操作的结果
39
+ * @throws 当存储操作失败时抛出错误
40
+ */
41
+ setItem<T>(key: string, value: T): Promise<void>;
42
+ /**
43
+ * 获取键对应的值
44
+ * @param key 要获取的键名
45
+ * @returns Promise<T> 返回存储的值,如果不存在则返回 undefined
46
+ * @throws 当获取操作失败时抛出错误
47
+ * @template T 存储值的类型,默认为 any
48
+ */
49
+ getItem<T = any>(key: string): Promise<T>;
50
+ }
51
+
52
+ export { IndexedDBStorage };
package/es/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { default as Cache, ICache, ICacheOptions, StorageMap, StorageType } from './cache/index.js';
2
+ export { ErrorHandlerReturnType, Options, RequestOptions, default as createBaseRequest } from './request/index.js';
3
+ export { createStoreGetter, createStoreGetterMemo } from './store/createGetter/index.js';
4
+ export { IHookStateInitAction, IHookStateInitialSetter, IHookStateResolvable, IHookStateSetAction, IHookStateSetter, default as createStateStore } from './store/createStateStore/index.js';
5
+ export { BaseValidator } from './validator/validator.js';
6
+ export { VArray, VBoolean, VEmail, VMax, VMaxLength, VMin, VMinLength, VNumber, VPattern, VRequired, VString } from './validator/decorators.js';
7
+ export { default as RequestError, RequestErrorType } from './request/error.js';
@@ -0,0 +1,31 @@
1
+ /**
2
+ * 请求错误类型
3
+ * - server: 服务端业务错误
4
+ * - http: HTTP 网络错误
5
+ */
6
+ type RequestErrorType = 'server' | 'http';
7
+ /**
8
+ * 请求错误类
9
+ * 用于统一处理请求过程中的各种错误
10
+ *
11
+ * @template Data 错误数据类型
12
+ * @extends Error
13
+ */
14
+ declare class RequestError<Data = any> extends Error {
15
+ /** 错误码 */
16
+ code: string;
17
+ /** 错误类型 */
18
+ type: RequestErrorType;
19
+ /** 错误相关的数据 */
20
+ data?: Data;
21
+ /**
22
+ * 构造函数
23
+ * @param message 错误消息
24
+ * @param type 错误类型
25
+ * @param data 错误相关的数据
26
+ */
27
+ constructor(message: string, type: RequestErrorType, data?: Data);
28
+ }
29
+
30
+ export { RequestError as default };
31
+ export type { RequestErrorType };
@@ -0,0 +1,140 @@
1
+ import { AxiosResponse, Method, AxiosRequestConfig } from 'axios';
2
+ import { StorageType } from '../cache/index.js';
3
+ export { default as RequestError, RequestErrorType } from './error.js';
4
+
5
+ /**
6
+ * 错误处理器返回类型
7
+ * @template D 响应数据类型
8
+ */
9
+ type ErrorHandlerReturnType<D> = {
10
+ /** 替换响应数据 */
11
+ replaceResData?: D;
12
+ /**
13
+ * 是否抛出错误
14
+ * - true: 强制抛出错误
15
+ * - false: 不抛出错误
16
+ * - 'default': 使用默认错误处理逻辑
17
+ */
18
+ throwError?: boolean | "default";
19
+ };
20
+ /**
21
+ * 请求配置选项接口
22
+ * @template Params 请求参数类型
23
+ * @template Data 响应数据类型
24
+ */
25
+ interface Options<Params = any, Data = any> {
26
+ /** 请求基础URL,默认为空字符串 */
27
+ baseURL?: string;
28
+ /**
29
+ * 是否抛出错误
30
+ * @default true
31
+ */
32
+ throwError?: boolean;
33
+ /**
34
+ * 默认的消息展示函数
35
+ * @default window.alert
36
+ */
37
+ defaultMessageShower?: (message: string) => void;
38
+ /**
39
+ * 是否启用缓存功能
40
+ * @default false
41
+ */
42
+ enableCache?: boolean;
43
+ /**
44
+ * 缓存键比较函数
45
+ * @default defaultEquals 使用 JSON.stringify 进行比较
46
+ */
47
+ cacheKeyEquals?: (prev: Params, next: Params) => boolean;
48
+ /**
49
+ * 是否将响应数据存入缓存
50
+ * @default false
51
+ */
52
+ cacheData?: boolean;
53
+ /**
54
+ * 缓存时间(秒)
55
+ * @default 60
56
+ */
57
+ cacheTime?: number;
58
+ /**
59
+ * 缓存数据的存储类型
60
+ * - localStorage: 使用浏览器本地存储,数据永久保存
61
+ * - sessionStorage: 使用会话存储,关闭浏览器后清除
62
+ * - indexedDB: 使用 IndexedDB 数据库存储
63
+ * - 不填则仅在内存中缓存,页面刷新后清除
64
+ */
65
+ cacheDataInStorage?: StorageType;
66
+ /**
67
+ * 缓存数据的键名
68
+ * @default `${method}:${baseURL}${url}` 默认使用请求方法、基础URL和请求路径组合
69
+ */
70
+ cacheDataKey?: string;
71
+ /**
72
+ * IndexedDB 数据库名称
73
+ * @default '__apiCacheDatabase__'
74
+ */
75
+ indexDBName?: string;
76
+ /**
77
+ * 错误码在响应数据中的路径
78
+ * @default 'code'
79
+ */
80
+ errorCodePath?: string;
81
+ /**
82
+ * 错误码映射表
83
+ * 可以配置错误码对应的错误信息或处理函数
84
+ * @default {} 空对象,使用默认处理函数
85
+ */
86
+ errorCodeMap?: Record<string, string | ((code: string, data: Data, res: AxiosResponse<Data>, requestParam: RequestOptions<Params>) => ErrorHandlerReturnType<Data> | void)>;
87
+ /**
88
+ * 默认错误码处理函数
89
+ * 当错误码不在 errorCodeMap 中时调用
90
+ */
91
+ defaultErrorCodeHandler?: (code: string, data: Data, res: AxiosResponse<Data>) => Promise<ErrorHandlerReturnType<Data> | void>;
92
+ /**
93
+ * 成功状态的错误码列表
94
+ * @default ['0', '200']
95
+ */
96
+ successCodes?: string[];
97
+ /**
98
+ * HTTP 错误码映射表
99
+ * 可以配置 HTTP 状态码对应的错误信息或处理函数
100
+ * @default {} 空对象,使用默认处理函数
101
+ */
102
+ httpErrorCodeMap?: Record<string, string | ((code: number, res: AxiosResponse<Data>, requestParam: RequestOptions<Params>) => Promise<ErrorHandlerReturnType<Data> | void>)>;
103
+ /**
104
+ * 默认 HTTP 错误码处理函数
105
+ * 当 HTTP 状态码不在 httpErrorCodeMap 中时调用
106
+ */
107
+ defaultHttpErrorCodeHandler?: (code: number, error: any) => Promise<ErrorHandlerReturnType<Data> | void>;
108
+ /**
109
+ * 其他错误处理函数
110
+ * 处理非 HTTP 错误和非业务错误码的错误
111
+ */
112
+ otherErrorHandler?: (error: any) => Promise<ErrorHandlerReturnType<Data> | void>;
113
+ axiosOptions?: Omit<AxiosRequestConfig<Params>, "method" | "url" | "params" | "data">;
114
+ }
115
+ /**
116
+ * 请求参数接口
117
+ * @template Param 请求参数类型
118
+ */
119
+ interface RequestOptions<Param> {
120
+ /** HTTP 请求方法 */
121
+ method: Method;
122
+ /** 请求URL */
123
+ url: string;
124
+ /** POST/PUT 等请求的数据 */
125
+ data?: Param;
126
+ /** URL 查询参数 */
127
+ params?: Param;
128
+ }
129
+ /**
130
+ * 创建基础请求实例
131
+ * @param baseOptions 基础配置选项
132
+ * @returns 请求创建函数
133
+ */
134
+ declare function createBaseRequest(baseOptions?: Options): <Param, Data extends Record<any, any>>(requestOptions: RequestOptions<Param>, createOptions?: Omit<Options<Param, Data>, "baseURL">) => {
135
+ (requestParam?: Omit<RequestOptions<Param>, "url" | "method">, options?: Omit<Options<Param, Data>, "baseURL" | "cacheDataKey" | "cacheDataInStorage" | "cacheKeyEquals">): Promise<Data>;
136
+ clearCache(): void;
137
+ };
138
+
139
+ export { createBaseRequest as default };
140
+ export type { ErrorHandlerReturnType, Options, RequestOptions };
@@ -0,0 +1,148 @@
1
+ import { __assign, __awaiter, __generator } from 'tslib';
2
+ import axios from 'axios';
3
+ import at from 'lodash-es/at';
4
+ import { _defaultErrorCodeHandler, _defaultHttpErrorCodeHandler, _defaultOtherErrorCodeHandler } from './defaultHandlers.mjs';
5
+ import defaultEquals from '../_utils/defaultEquals.mjs';
6
+ import Cache from '../cache/index.mjs';
7
+ import RequestError from './error.mjs';
8
+
9
+ /**
10
+ * 创建基础请求实例
11
+ * @param baseOptions 基础配置选项
12
+ * @returns 请求创建函数
13
+ */
14
+ function createBaseRequest(baseOptions) {
15
+ var baseURL = Object(baseOptions).baseURL;
16
+ // 创建新的 Axios 实例并配置基础URL和跨域凭证
17
+ var instance = axios.create({
18
+ baseURL: baseURL,
19
+ withCredentials: true,
20
+ });
21
+ /**
22
+ * 创建请求函数
23
+ * @template Param 请求参数类型
24
+ * @template Data 响应数据类型,必须是对象类型
25
+ * @param requestOptions 请求配置
26
+ * @param createOptions 创建选项(覆盖基础配置)
27
+ * @returns 发送请求的函数
28
+ */
29
+ return function createRequest(requestOptions, createOptions) {
30
+ var _a = __assign({}, requestOptions), method = _a.method, url = _a.url;
31
+ var _b = __assign(__assign({}, baseOptions), createOptions), baseURL = _b.baseURL, _c = _b.cacheDataKey, cacheDataKey = _c === void 0 ? "".concat(method, ":").concat(baseURL).concat(url) : _c, cacheDataInStorage = _b.cacheDataInStorage, _d = _b.cacheKeyEquals, cacheKeyEquals = _d === void 0 ? defaultEquals : _d, cacheTime = _b.cacheTime, _e = _b.indexDBName, indexDBName = _e === void 0 ? "__apiCacheDatabase__" : _e;
32
+ var cache = new Cache(cacheDataInStorage, cacheDataKey, cacheTime, indexDBName, cacheKeyEquals);
33
+ function request(requestParam, options) {
34
+ var _this = this;
35
+ var _a = __assign(__assign({}, requestOptions), requestParam), method = _a.method, url = _a.url, _b = _a.data, data = _b === void 0 ? {} : _b, _c = _a.params, params = _c === void 0 ? {} : _c;
36
+ var requestDataOrParams = params;
37
+ if (method.toLowerCase() === "post") {
38
+ requestDataOrParams = data;
39
+ }
40
+ var _d = __assign(__assign(__assign({}, baseOptions), createOptions), options).defaultMessageShower, defaultMessageShower = _d === void 0 ? console.error : _d;
41
+ var _e = __assign(__assign(__assign({}, baseOptions), createOptions), options), _f = _e.enableCache, enableCache = _f === void 0 ? false : _f, _g = _e.cacheData, cacheData = _g === void 0 ? false : _g, _h = _e.defaultErrorCodeHandler, defaultErrorCodeHandler = _h === void 0 ? _defaultErrorCodeHandler.bind(null, defaultMessageShower) : _h, _j = _e.defaultHttpErrorCodeHandler, defaultHttpErrorCodeHandler = _j === void 0 ? _defaultHttpErrorCodeHandler.bind(null, defaultMessageShower) : _j, _k = _e.otherErrorHandler, otherErrorHandler = _k === void 0 ? _defaultOtherErrorCodeHandler.bind(null, defaultMessageShower) : _k, _l = _e.errorCodePath, errorCodePath = _l === void 0 ? "code" : _l, _m = _e.cacheTime, cacheTime = _m === void 0 ? 60 : _m, _o = _e.errorCodeMap, errorCodeMap = _o === void 0 ? {} : _o, _p = _e.successCodes, successCodes = _p === void 0 ? ["0", "200"] : _p, _q = _e.httpErrorCodeMap, httpErrorCodeMap = _q === void 0 ? {} : _q, _r = _e.axiosOptions, axiosOptions = _r === void 0 ? {} : _r, _s = _e.throwError, throwError = _s === void 0 ? true : _s;
42
+ if (enableCache) {
43
+ var cacheItem = cache.getCache(requestDataOrParams);
44
+ if (cacheItem) {
45
+ return Promise.resolve(cacheItem);
46
+ }
47
+ }
48
+ return instance
49
+ .request(__assign({ method: method, url: url, data: data, params: params }, axiosOptions))
50
+ .then(function (res) { return __awaiter(_this, void 0, void 0, function () {
51
+ var errorCode, _a, _b, _c, customHandler, err, _d, _e, replaceResData, _f, handlerThrowError, _g;
52
+ return __generator(this, function (_h) {
53
+ switch (_h.label) {
54
+ case 0:
55
+ errorCode = String(at(res.data, errorCodePath));
56
+ if (successCodes.includes(errorCode)) {
57
+ if (cacheData) {
58
+ cache.setCache(requestDataOrParams, res.data, { cacheTime: cacheTime });
59
+ }
60
+ return [2 /*return*/, res.data];
61
+ }
62
+ _a = errorCodeMap, _b = errorCode, _c = _a[_b], customHandler = _c === void 0 ? defaultErrorCodeHandler : _c;
63
+ err = new RequestError("服务端错误", "server", res);
64
+ if (!(typeof customHandler === "string")) return [3 /*break*/, 1];
65
+ defaultMessageShower(customHandler);
66
+ return [3 /*break*/, 3];
67
+ case 1:
68
+ _g = Object;
69
+ return [4 /*yield*/, customHandler(errorCode, res.data, res, __assign(__assign({}, requestOptions), requestParam))];
70
+ case 2:
71
+ _d = _g.apply(void 0, [(_h.sent())]), _e = _d.replaceResData, replaceResData = _e === void 0 ? res.data : _e, _f = _d.throwError, handlerThrowError = _f === void 0 ? "default" : _f;
72
+ res.data = replaceResData;
73
+ switch (handlerThrowError) {
74
+ case true:
75
+ throw err;
76
+ case false:
77
+ return [2 /*return*/, res.data];
78
+ }
79
+ _h.label = 3;
80
+ case 3:
81
+ if (throwError) {
82
+ throw err;
83
+ }
84
+ return [2 /*return*/, res.data];
85
+ }
86
+ });
87
+ }); }, function (error) { return __awaiter(_this, void 0, void 0, function () {
88
+ var resData, _a, _b, _c, customHandler, err, _d, _e, replaceResData, _f, handlerThrowError, _g, resData, err, _h, _j, replaceResData, _k, handlerThrowError, _l;
89
+ return __generator(this, function (_m) {
90
+ switch (_m.label) {
91
+ case 0:
92
+ if (!error.response) return [3 /*break*/, 4];
93
+ resData = error;
94
+ _a = httpErrorCodeMap, _b = error.response.status, _c = _a[_b], customHandler = _c === void 0 ? defaultHttpErrorCodeHandler : _c;
95
+ err = new RequestError("服务端错误", "http", error);
96
+ if (!(typeof customHandler === "string")) return [3 /*break*/, 1];
97
+ defaultMessageShower(customHandler);
98
+ return [3 /*break*/, 3];
99
+ case 1:
100
+ _g = Object;
101
+ return [4 /*yield*/, customHandler(error.response.status, error, __assign(__assign({}, requestOptions), requestParam))];
102
+ case 2:
103
+ _d = _g.apply(void 0, [(_m.sent())]), _e = _d.replaceResData, replaceResData = _e === void 0 ? error : _e, _f = _d.throwError, handlerThrowError = _f === void 0 ? "default" : _f;
104
+ resData = replaceResData;
105
+ switch (handlerThrowError) {
106
+ case true:
107
+ throw err;
108
+ case false:
109
+ return [2 /*return*/, resData];
110
+ }
111
+ _m.label = 3;
112
+ case 3:
113
+ if (throwError) {
114
+ throw err;
115
+ }
116
+ return [2 /*return*/, resData];
117
+ case 4:
118
+ resData = error;
119
+ err = new RequestError("服务端错误", "http", error);
120
+ err.type = "http";
121
+ err.data = error;
122
+ _l = Object;
123
+ return [4 /*yield*/, otherErrorHandler(error)];
124
+ case 5:
125
+ _h = (_l.apply(void 0, [(_m.sent())])), _j = _h.replaceResData, replaceResData = _j === void 0 ? error : _j, _k = _h.throwError, handlerThrowError = _k === void 0 ? "default" : _k;
126
+ resData = replaceResData;
127
+ switch (handlerThrowError) {
128
+ case true:
129
+ throw err;
130
+ case false:
131
+ return [2 /*return*/, resData];
132
+ }
133
+ if (throwError) {
134
+ throw err;
135
+ }
136
+ return [2 /*return*/, resData];
137
+ }
138
+ });
139
+ }); });
140
+ }
141
+ request.clearCache = function () {
142
+ cache.clear();
143
+ };
144
+ return request;
145
+ };
146
+ }
147
+
148
+ export { createBaseRequest as default };
@@ -0,0 +1,30 @@
1
+ import createStateStore from '../createStateStore/index.js';
2
+
3
+ type StoreGetter<S = any> = {
4
+ [K in string]: (store: S) => any;
5
+ };
6
+ type GetterNameMap<G extends StoreGetter<any>> = {
7
+ [K in keyof G]: string;
8
+ };
9
+ type ReducedData<G extends StoreGetter<any>, M extends GetterNameMap<G>> = {
10
+ [K in keyof M as M[K]]: G[K extends keyof G ? K : never] extends (store: any) => infer R ? R : never;
11
+ };
12
+ /**
13
+ * 创建 store getter
14
+ * @param store store实例
15
+ * @param getters getter函数
16
+ * @param getterNameMaps 将 getter 函数和 getter 名称一一映射
17
+ * @returns getter object
18
+ */
19
+ declare const createStoreGetter: <S, G extends StoreGetter<S>, M extends GetterNameMap<G>>(store: ReturnType<typeof createStateStore<S>>, getters: G, getterNameMaps: M) => ReducedData<G, M>;
20
+ /**
21
+ *
22
+ * @param store store实例
23
+ * @param getters getter函数
24
+ * @param getterNameMaps 将 getter 函数和 getter 名称一一映射
25
+ * @returns getter memo hook
26
+ */
27
+ declare const createStoreGetterMemo: <S, G extends StoreGetter<S>, M extends GetterNameMap<G>>(store: ReturnType<typeof createStateStore<S>>, getters: G, getterNameMaps: M) => () => ReducedData<G, M>;
28
+
29
+ export { createStoreGetter, createStoreGetterMemo };
30
+ export type { GetterNameMap, ReducedData, StoreGetter };