@ruan-cat/utils 4.3.2 → 4.5.0

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.
package/dist/index.d.ts CHANGED
@@ -18,6 +18,15 @@ type Conditions = Condition[];
18
18
  declare function isConditionsEvery(conditions: Condition[]): boolean;
19
19
  declare function isConditionsSome(conditions: Condition[]): boolean;
20
20
 
21
+ /**
22
+ * 一个简单的格式化函数
23
+ * @description
24
+ * 用于将复杂对象变成纯文本 打印出来
25
+ *
26
+ * 主要用于测试框架打印完整的内容
27
+ */
28
+ declare function printFormat(params: any): any;
29
+
21
30
  /** 创建简单的异步任务 */
22
31
  declare function generateSimpleAsyncTask<T extends (...args: any) => any>(func: T): (...args: any) => Promise<ReturnType<T>>;
23
32
  type SimpleAsyncTask = ReturnType<typeof generateSimpleAsyncTask>;
@@ -107,4 +116,4 @@ type Prettify<T> = {
107
116
  */
108
117
  type ToNumberLike<T extends number> = T | `${T}`;
109
118
 
110
- export { type BaseTask, type Condition, type Conditions, type ParallelTasks, type PnpmWorkspace, type Prettify, type PromiseTasksConfig, type QueueTasks, type SimpleAsyncTask, type SingleTasks, type Task, type TaskType, type TasksConfig, type ToNumberLike, definePromiseTasks, executePromiseTasks, generateSimpleAsyncTask, initFlag, isConditionsEvery, isConditionsSome, runPromiseByConcurrency, runPromiseByQueue, taskTypes };
119
+ export { type BaseTask, type Condition, type Conditions, type ParallelTasks, type PnpmWorkspace, type Prettify, type PromiseTasksConfig, type QueueTasks, type SimpleAsyncTask, type SingleTasks, type Task, type TaskType, type TasksConfig, type ToNumberLike, definePromiseTasks, executePromiseTasks, generateSimpleAsyncTask, initFlag, isConditionsEvery, isConditionsSome, printFormat, runPromiseByConcurrency, runPromiseByQueue, taskTypes };
package/dist/index.js CHANGED
@@ -6,6 +6,19 @@ function isConditionsSome(conditions) {
6
6
  return conditions.some((condition) => condition());
7
7
  }
8
8
 
9
+ // src/print.ts
10
+ import { isPlainObject, isArray } from "lodash-es";
11
+ function printFormat(params) {
12
+ const boolRes = isConditionsSome([
13
+ // 是不是纯对象?
14
+ () => isPlainObject(params),
15
+ // 或者是不是单纯的数组?
16
+ () => isArray(params)
17
+ ]);
18
+ const res = boolRes ? JSON.stringify(params, null, 2) : params;
19
+ return res;
20
+ }
21
+
9
22
  // src/define-promise-tasks.ts
10
23
  var taskTypes = ["single", "parallel", "queue"];
11
24
  function isSingleTasks(config) {
@@ -80,6 +93,7 @@ export {
80
93
  initFlag,
81
94
  isConditionsEvery,
82
95
  isConditionsSome,
96
+ printFormat,
83
97
  runPromiseByConcurrency,
84
98
  runPromiseByQueue,
85
99
  taskTypes
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/conditions.ts","../src/define-promise-tasks.ts","../src/simple-promise-tools.ts"],"sourcesContent":["export type Condition = (...args: unknown[]) => boolean;\n\n/** @deprecated 没必要 */\nexport type Conditions = Condition[];\n\n/**\n * 是否每一个条件函数都满足?\n * @description\n * ### 设计理由\n * 旨在于封装这样的代码段\n * ```js\n * const conditions = [\n * \t() => !isEqual(nAssetRecord, oAssetRecord),\n * \t() => !isEqual(nAssetRecord, defPropsAssets),\n * \t() => isEdit.value || isInfo.value,\n * ];\n * conditions.every((condition) => condition())\n * ```\n */\nexport function isConditionsEvery(conditions: Condition[]) {\n\treturn conditions.every((condition) => condition());\n}\n\nexport function isConditionsSome(conditions: Condition[]) {\n\treturn conditions.some((condition) => condition());\n}\n","import { type SimpleAsyncTask } from \"./simple-promise-tools\";\n\nexport const taskTypes = <const>[\"single\", \"parallel\", \"queue\"];\n\nexport type TaskType = (typeof taskTypes)[number];\n\nexport interface BaseTask {\n\t/** 任务类型 */\n\ttype: TaskType;\n}\n\nexport type Task = SimpleAsyncTask | TasksConfig;\n\nexport interface SingleTasks extends BaseTask {\n\ttype: \"single\";\n\ttasks: Task;\n}\n\nexport interface ParallelTasks extends BaseTask {\n\ttype: \"parallel\";\n\ttasks: Task[];\n}\n\nexport interface QueueTasks extends BaseTask {\n\ttype: \"queue\";\n\ttasks: Task[];\n}\n\nexport type TasksConfig = SingleTasks | ParallelTasks | QueueTasks;\n\nexport type PromiseTasksConfig = TasksConfig;\n\nfunction isSingleTasks(config: TasksConfig): config is SingleTasks {\n\treturn config.type === \"single\";\n}\n\nfunction isParallelTasks(config: TasksConfig): config is ParallelTasks {\n\treturn config.type === \"parallel\";\n}\n\nfunction isQueueTasks(config: TasksConfig): config is QueueTasks {\n\treturn config.type === \"queue\";\n}\n\nfunction isSimpleAsyncTask(config: Task): config is SimpleAsyncTask {\n\treturn typeof config === \"function\";\n}\n\nfunction isTasksConfig(config: Task): config is TasksConfig {\n\treturn typeof config === \"object\";\n}\n\n/**\n * 定义异步任务对象\n * @description\n * 这个对象是一揽子异步任务的配置\n */\nexport function definePromiseTasks(config: TasksConfig) {\n\treturn config;\n}\n\n/**\n * @private 一个工具函数 用于生成异步函数数组\n * @deprecated 在处理串行任务时 疑似有故障\n */\nfunction getPromises(tasks: Task[]): ((...args: any) => Promise<any>)[] {\n\treturn tasks.map((task) => {\n\t\treturn async function (...args: any) {\n\t\t\tif (isSimpleAsyncTask(task)) {\n\t\t\t\treturn await task(...args);\n\t\t\t} else {\n\t\t\t\treturn await executePromiseTasks(task);\n\t\t\t}\n\t\t};\n\t});\n}\n\n/**\n * 执行异步函数对象\n */\nexport async function executePromiseTasks(\n\tconfig: TasksConfig,\n\t/**\n\t * 上一次递归执行时提供的参数\n\t * @description\n\t * 考虑到递归函数 这里提供了一个参数 用于传递上一次递归执行的结果\n\t */\n\tlastParams: any = null,\n): Promise<any> {\n\tif (isSingleTasks(config)) {\n\t\tif (isSimpleAsyncTask(config.tasks)) {\n\t\t\t// 实际执行的 tasks 往往是无参函数 这里为了保险,故主动传递参数\n\t\t\treturn await config.tasks(lastParams);\n\t\t}\n\n\t\treturn await executePromiseTasks(config.tasks, lastParams);\n\t}\n\n\tif (isParallelTasks(config)) {\n\t\treturn await Promise.all(\n\t\t\tconfig.tasks.map((task) => {\n\t\t\t\tif (isSimpleAsyncTask(task)) {\n\t\t\t\t\t// console.log(` 并行任务遇到单独的异步函数 `);\n\t\t\t\t\treturn task(lastParams);\n\t\t\t\t}\n\n\t\t\t\t// console.log(` 并行任务遇到嵌套结构 `);\n\t\t\t\treturn executePromiseTasks(task, lastParams);\n\t\t\t}),\n\t\t);\n\t}\n\n\tif (isQueueTasks(config)) {\n\t\tlet res: Awaited<any>;\n\t\tfor await (const task of config.tasks) {\n\t\t\tif (isSimpleAsyncTask(task)) {\n\t\t\t\t// console.log(` 串行任务遇到单独的异步函数 `);\n\n\t\t\t\tres = await task(lastParams);\n\t\t\t\tlastParams = res;\n\t\t\t\t// console.log(` 串行任务 单独 res `, res);\n\t\t\t} else {\n\t\t\t\tres = await executePromiseTasks(task, lastParams);\n\t\t\t\tlastParams = res;\n\t\t\t\t// console.log(` 串行任务 配置 res `, res);\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n}\n","// import { uniqueId } from \"lodash-es\";\n// const getCounter = () => uniqueId();\n\n/** 创建简单的异步任务 */\nexport function generateSimpleAsyncTask<T extends (...args: any) => any>(func: T) {\n\t// const taskId = getCounter();\n\n\treturn function (...args: any) {\n\t\t// consola.info(` 这是第 ${taskId} 个异步任务 `);\n\t\t// consola.start(\" 这里是新创建的异步函数 检查参数: \", ...args);\n\n\t\treturn new Promise<ReturnType<T>>((resolve, reject) => {\n\t\t\t// consola.start(\" 内部promise 检查参数: \", ...args);\n\t\t\tresolve(func(...args));\n\t\t});\n\t};\n}\n\nexport type SimpleAsyncTask = ReturnType<typeof generateSimpleAsyncTask>;\n\nexport const initFlag = <const>\"initFlag\";\n\n/**\n * 以队列串行的形式 串行运行异步函数\n * @see https://github.com/ascoders/weekly/blob/master/前沿技术/77.精读《用%20Reduce%20实现%20Promise%20串行执行》.md\n * @version 1\n */\nasync function runPromiseByQueueV1<T>(promises: ((...args: any) => Promise<T>)[]) {\n\tpromises.reduce(\n\t\tasync function (previousPromise, nextPromise, currentIndex) {\n\t\t\tconst response = await previousPromise;\n\t\t\t// consola.log(` reduce串行函数 currentIndex= ${currentIndex} res =`, response);\n\t\t\treturn await nextPromise(response);\n\t\t},\n\t\tPromise.resolve(initFlag) as Promise<any>,\n\t);\n}\n\n/**\n * 以队列串行的形式 串行运行异步函数\n * @version 2\n */\nexport async function runPromiseByQueue<T>(promises: ((...args: any) => Promise<T>)[]) {\n\tlet response: typeof initFlag | Awaited<T> = initFlag;\n\tfor await (const promise of promises) {\n\t\tresponse = await promise(response);\n\t}\n}\n\n/**\n * 以并行的形式 并发运行异步函数\n */\nexport async function runPromiseByConcurrency<T>(promises: ((...args: any) => Promise<T>)[]) {\n\tawait Promise.all(promises.map((promise) => promise()));\n}\n"],"mappings":";AAmBO,SAAS,kBAAkB,YAAyB;AAC1D,SAAO,WAAW,MAAM,CAAC,cAAc,UAAU,CAAC;AACnD;AAEO,SAAS,iBAAiB,YAAyB;AACzD,SAAO,WAAW,KAAK,CAAC,cAAc,UAAU,CAAC;AAClD;;;ACvBO,IAAM,YAAmB,CAAC,UAAU,YAAY,OAAO;AA8B9D,SAAS,cAAc,QAA4C;AAClE,SAAO,OAAO,SAAS;AACxB;AAEA,SAAS,gBAAgB,QAA8C;AACtE,SAAO,OAAO,SAAS;AACxB;AAEA,SAAS,aAAa,QAA2C;AAChE,SAAO,OAAO,SAAS;AACxB;AAEA,SAAS,kBAAkB,QAAyC;AACnE,SAAO,OAAO,WAAW;AAC1B;AAWO,SAAS,mBAAmB,QAAqB;AACvD,SAAO;AACR;AAqBA,eAAsB,oBACrB,QAMA,aAAkB,MACH;AACf,MAAI,cAAc,MAAM,GAAG;AAC1B,QAAI,kBAAkB,OAAO,KAAK,GAAG;AAEpC,aAAO,MAAM,OAAO,MAAM,UAAU;AAAA,IACrC;AAEA,WAAO,MAAM,oBAAoB,OAAO,OAAO,UAAU;AAAA,EAC1D;AAEA,MAAI,gBAAgB,MAAM,GAAG;AAC5B,WAAO,MAAM,QAAQ;AAAA,MACpB,OAAO,MAAM,IAAI,CAAC,SAAS;AAC1B,YAAI,kBAAkB,IAAI,GAAG;AAE5B,iBAAO,KAAK,UAAU;AAAA,QACvB;AAGA,eAAO,oBAAoB,MAAM,UAAU;AAAA,MAC5C,CAAC;AAAA,IACF;AAAA,EACD;AAEA,MAAI,aAAa,MAAM,GAAG;AACzB,QAAI;AACJ,qBAAiB,QAAQ,OAAO,OAAO;AACtC,UAAI,kBAAkB,IAAI,GAAG;AAG5B,cAAM,MAAM,KAAK,UAAU;AAC3B,qBAAa;AAAA,MAEd,OAAO;AACN,cAAM,MAAM,oBAAoB,MAAM,UAAU;AAChD,qBAAa;AAAA,MAEd;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;;;AC9HO,SAAS,wBAAyD,MAAS;AAGjF,SAAO,YAAa,MAAW;AAI9B,WAAO,IAAI,QAAuB,CAAC,SAAS,WAAW;AAEtD,cAAQ,KAAK,GAAG,IAAI,CAAC;AAAA,IACtB,CAAC;AAAA,EACF;AACD;AAIO,IAAM,WAAkB;AAsB/B,eAAsB,kBAAqB,UAA4C;AACtF,MAAI,WAAyC;AAC7C,mBAAiB,WAAW,UAAU;AACrC,eAAW,MAAM,QAAQ,QAAQ;AAAA,EAClC;AACD;AAKA,eAAsB,wBAA2B,UAA4C;AAC5F,QAAM,QAAQ,IAAI,SAAS,IAAI,CAAC,YAAY,QAAQ,CAAC,CAAC;AACvD;","names":[]}
1
+ {"version":3,"sources":["../src/conditions.ts","../src/print.ts","../src/define-promise-tasks.ts","../src/simple-promise-tools.ts"],"sourcesContent":["export type Condition = (...args: unknown[]) => boolean;\n\n/** @deprecated 没必要 */\nexport type Conditions = Condition[];\n\n/**\n * 是否每一个条件函数都满足?\n * @description\n * ### 设计理由\n * 旨在于封装这样的代码段\n * ```js\n * const conditions = [\n * \t() => !isEqual(nAssetRecord, oAssetRecord),\n * \t() => !isEqual(nAssetRecord, defPropsAssets),\n * \t() => isEdit.value || isInfo.value,\n * ];\n * conditions.every((condition) => condition())\n * ```\n */\nexport function isConditionsEvery(conditions: Condition[]) {\n\treturn conditions.every((condition) => condition());\n}\n\nexport function isConditionsSome(conditions: Condition[]) {\n\treturn conditions.some((condition) => condition());\n}\n","import { isPlainObject, isArray } from \"lodash-es\";\nimport { isConditionsSome } from \"./conditions\";\n\n/**\n * 一个简单的格式化函数\n * @description\n * 用于将复杂对象变成纯文本 打印出来\n *\n * 主要用于测试框架打印完整的内容\n */\nexport function printFormat(params: any) {\n\tconst boolRes = isConditionsSome([\n\t\t// 是不是纯对象?\n\t\t() => isPlainObject(params),\n\t\t// 或者是不是单纯的数组?\n\t\t() => isArray(params),\n\t]);\n\n\t// 如果是纯对象或者数组,则使用 JSON.stringify 格式化输出 否则原样返回\n\tconst res = boolRes ? JSON.stringify(params, null, 2) : params;\n\n\treturn res;\n}\n","import { type SimpleAsyncTask } from \"./simple-promise-tools\";\n\nexport const taskTypes = <const>[\"single\", \"parallel\", \"queue\"];\n\nexport type TaskType = (typeof taskTypes)[number];\n\nexport interface BaseTask {\n\t/** 任务类型 */\n\ttype: TaskType;\n}\n\nexport type Task = SimpleAsyncTask | TasksConfig;\n\nexport interface SingleTasks extends BaseTask {\n\ttype: \"single\";\n\ttasks: Task;\n}\n\nexport interface ParallelTasks extends BaseTask {\n\ttype: \"parallel\";\n\ttasks: Task[];\n}\n\nexport interface QueueTasks extends BaseTask {\n\ttype: \"queue\";\n\ttasks: Task[];\n}\n\nexport type TasksConfig = SingleTasks | ParallelTasks | QueueTasks;\n\nexport type PromiseTasksConfig = TasksConfig;\n\nfunction isSingleTasks(config: TasksConfig): config is SingleTasks {\n\treturn config.type === \"single\";\n}\n\nfunction isParallelTasks(config: TasksConfig): config is ParallelTasks {\n\treturn config.type === \"parallel\";\n}\n\nfunction isQueueTasks(config: TasksConfig): config is QueueTasks {\n\treturn config.type === \"queue\";\n}\n\nfunction isSimpleAsyncTask(config: Task): config is SimpleAsyncTask {\n\treturn typeof config === \"function\";\n}\n\nfunction isTasksConfig(config: Task): config is TasksConfig {\n\treturn typeof config === \"object\";\n}\n\n/**\n * 定义异步任务对象\n * @description\n * 这个对象是一揽子异步任务的配置\n */\nexport function definePromiseTasks(config: TasksConfig) {\n\treturn config;\n}\n\n/**\n * @private 一个工具函数 用于生成异步函数数组\n * @deprecated 在处理串行任务时 疑似有故障\n */\nfunction getPromises(tasks: Task[]): ((...args: any) => Promise<any>)[] {\n\treturn tasks.map((task) => {\n\t\treturn async function (...args: any) {\n\t\t\tif (isSimpleAsyncTask(task)) {\n\t\t\t\treturn await task(...args);\n\t\t\t} else {\n\t\t\t\treturn await executePromiseTasks(task);\n\t\t\t}\n\t\t};\n\t});\n}\n\n/**\n * 执行异步函数对象\n */\nexport async function executePromiseTasks(\n\tconfig: TasksConfig,\n\t/**\n\t * 上一次递归执行时提供的参数\n\t * @description\n\t * 考虑到递归函数 这里提供了一个参数 用于传递上一次递归执行的结果\n\t */\n\tlastParams: any = null,\n): Promise<any> {\n\tif (isSingleTasks(config)) {\n\t\tif (isSimpleAsyncTask(config.tasks)) {\n\t\t\t// 实际执行的 tasks 往往是无参函数 这里为了保险,故主动传递参数\n\t\t\treturn await config.tasks(lastParams);\n\t\t}\n\n\t\treturn await executePromiseTasks(config.tasks, lastParams);\n\t}\n\n\tif (isParallelTasks(config)) {\n\t\treturn await Promise.all(\n\t\t\tconfig.tasks.map((task) => {\n\t\t\t\tif (isSimpleAsyncTask(task)) {\n\t\t\t\t\t// console.log(` 并行任务遇到单独的异步函数 `);\n\t\t\t\t\treturn task(lastParams);\n\t\t\t\t}\n\n\t\t\t\t// console.log(` 并行任务遇到嵌套结构 `);\n\t\t\t\treturn executePromiseTasks(task, lastParams);\n\t\t\t}),\n\t\t);\n\t}\n\n\tif (isQueueTasks(config)) {\n\t\tlet res: Awaited<any>;\n\t\tfor await (const task of config.tasks) {\n\t\t\tif (isSimpleAsyncTask(task)) {\n\t\t\t\t// console.log(` 串行任务遇到单独的异步函数 `);\n\n\t\t\t\tres = await task(lastParams);\n\t\t\t\tlastParams = res;\n\t\t\t\t// console.log(` 串行任务 单独 res `, res);\n\t\t\t} else {\n\t\t\t\tres = await executePromiseTasks(task, lastParams);\n\t\t\t\tlastParams = res;\n\t\t\t\t// console.log(` 串行任务 配置 res `, res);\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n}\n","// import { uniqueId } from \"lodash-es\";\n// const getCounter = () => uniqueId();\n\n/** 创建简单的异步任务 */\nexport function generateSimpleAsyncTask<T extends (...args: any) => any>(func: T) {\n\t// const taskId = getCounter();\n\n\treturn function (...args: any) {\n\t\t// consola.info(` 这是第 ${taskId} 个异步任务 `);\n\t\t// consola.start(\" 这里是新创建的异步函数 检查参数: \", ...args);\n\n\t\treturn new Promise<ReturnType<T>>((resolve, reject) => {\n\t\t\t// consola.start(\" 内部promise 检查参数: \", ...args);\n\t\t\tresolve(func(...args));\n\t\t});\n\t};\n}\n\nexport type SimpleAsyncTask = ReturnType<typeof generateSimpleAsyncTask>;\n\nexport const initFlag = <const>\"initFlag\";\n\n/**\n * 以队列串行的形式 串行运行异步函数\n * @see https://github.com/ascoders/weekly/blob/master/前沿技术/77.精读《用%20Reduce%20实现%20Promise%20串行执行》.md\n * @version 1\n */\nasync function runPromiseByQueueV1<T>(promises: ((...args: any) => Promise<T>)[]) {\n\tpromises.reduce(\n\t\tasync function (previousPromise, nextPromise, currentIndex) {\n\t\t\tconst response = await previousPromise;\n\t\t\t// consola.log(` reduce串行函数 currentIndex= ${currentIndex} res =`, response);\n\t\t\treturn await nextPromise(response);\n\t\t},\n\t\tPromise.resolve(initFlag) as Promise<any>,\n\t);\n}\n\n/**\n * 以队列串行的形式 串行运行异步函数\n * @version 2\n */\nexport async function runPromiseByQueue<T>(promises: ((...args: any) => Promise<T>)[]) {\n\tlet response: typeof initFlag | Awaited<T> = initFlag;\n\tfor await (const promise of promises) {\n\t\tresponse = await promise(response);\n\t}\n}\n\n/**\n * 以并行的形式 并发运行异步函数\n */\nexport async function runPromiseByConcurrency<T>(promises: ((...args: any) => Promise<T>)[]) {\n\tawait Promise.all(promises.map((promise) => promise()));\n}\n"],"mappings":";AAmBO,SAAS,kBAAkB,YAAyB;AAC1D,SAAO,WAAW,MAAM,CAAC,cAAc,UAAU,CAAC;AACnD;AAEO,SAAS,iBAAiB,YAAyB;AACzD,SAAO,WAAW,KAAK,CAAC,cAAc,UAAU,CAAC;AAClD;;;ACzBA,SAAS,eAAe,eAAe;AAUhC,SAAS,YAAY,QAAa;AACxC,QAAM,UAAU,iBAAiB;AAAA;AAAA,IAEhC,MAAM,cAAc,MAAM;AAAA;AAAA,IAE1B,MAAM,QAAQ,MAAM;AAAA,EACrB,CAAC;AAGD,QAAM,MAAM,UAAU,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI;AAExD,SAAO;AACR;;;ACpBO,IAAM,YAAmB,CAAC,UAAU,YAAY,OAAO;AA8B9D,SAAS,cAAc,QAA4C;AAClE,SAAO,OAAO,SAAS;AACxB;AAEA,SAAS,gBAAgB,QAA8C;AACtE,SAAO,OAAO,SAAS;AACxB;AAEA,SAAS,aAAa,QAA2C;AAChE,SAAO,OAAO,SAAS;AACxB;AAEA,SAAS,kBAAkB,QAAyC;AACnE,SAAO,OAAO,WAAW;AAC1B;AAWO,SAAS,mBAAmB,QAAqB;AACvD,SAAO;AACR;AAqBA,eAAsB,oBACrB,QAMA,aAAkB,MACH;AACf,MAAI,cAAc,MAAM,GAAG;AAC1B,QAAI,kBAAkB,OAAO,KAAK,GAAG;AAEpC,aAAO,MAAM,OAAO,MAAM,UAAU;AAAA,IACrC;AAEA,WAAO,MAAM,oBAAoB,OAAO,OAAO,UAAU;AAAA,EAC1D;AAEA,MAAI,gBAAgB,MAAM,GAAG;AAC5B,WAAO,MAAM,QAAQ;AAAA,MACpB,OAAO,MAAM,IAAI,CAAC,SAAS;AAC1B,YAAI,kBAAkB,IAAI,GAAG;AAE5B,iBAAO,KAAK,UAAU;AAAA,QACvB;AAGA,eAAO,oBAAoB,MAAM,UAAU;AAAA,MAC5C,CAAC;AAAA,IACF;AAAA,EACD;AAEA,MAAI,aAAa,MAAM,GAAG;AACzB,QAAI;AACJ,qBAAiB,QAAQ,OAAO,OAAO;AACtC,UAAI,kBAAkB,IAAI,GAAG;AAG5B,cAAM,MAAM,KAAK,UAAU;AAC3B,qBAAa;AAAA,MAEd,OAAO;AACN,cAAM,MAAM,oBAAoB,MAAM,UAAU;AAChD,qBAAa;AAAA,MAEd;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;;;AC9HO,SAAS,wBAAyD,MAAS;AAGjF,SAAO,YAAa,MAAW;AAI9B,WAAO,IAAI,QAAuB,CAAC,SAAS,WAAW;AAEtD,cAAQ,KAAK,GAAG,IAAI,CAAC;AAAA,IACtB,CAAC;AAAA,EACF;AACD;AAIO,IAAM,WAAkB;AAsB/B,eAAsB,kBAAqB,UAA4C;AACtF,MAAI,WAAyC;AAC7C,mBAAiB,WAAW,UAAU;AACrC,eAAW,MAAM,QAAQ,QAAQ;AAAA,EAClC;AACD;AAKA,eAAsB,wBAA2B,UAA4C;AAC5F,QAAM,QAAQ,IAAI,SAAS,IAAI,CAAC,YAAY,QAAQ,CAAC,CAAC;AACvD;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruan-cat/utils",
3
- "version": "4.3.2",
3
+ "version": "4.5.0",
4
4
  "description": "阮喵喵工具集合。默认提供js文件,也直接提供ts文件。",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -32,6 +32,7 @@
32
32
  "./unplugin-vue-router": "./src/unplugin-vue-router/index.ts",
33
33
  "./vite-plugin-autogeneration-import-file": "./src/vite-plugin-autogeneration-import-file/index.ts",
34
34
  "./vueuse": "./src/vueuse/index.ts",
35
+ "./vueuse/*": "./src/vueuse/*",
35
36
  "./src/*": "./src/*",
36
37
  "./dist/*": "./dist/*"
37
38
  },
@@ -78,6 +79,7 @@
78
79
  "typedoc-plugin-frontmatter": "^1.3.0",
79
80
  "typedoc-plugin-markdown": "^4.5.0",
80
81
  "typescript": "^5.8.2",
82
+ "unplugin-auto-import": "^19.1.1",
81
83
  "unplugin-vue-router": "^0.12.0",
82
84
  "vite-plugin-autogeneration-import-file": "^3.0.0",
83
85
  "vitepress": "^1.6.3"
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./conditions";
2
+ export * from "./print";
2
3
  export * from "./define-promise-tasks";
3
4
  export * from "./simple-promise-tools";
4
5
 
package/src/print.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { isPlainObject, isArray } from "lodash-es";
2
+ import { isConditionsSome } from "./conditions";
3
+
4
+ /**
5
+ * 一个简单的格式化函数
6
+ * @description
7
+ * 用于将复杂对象变成纯文本 打印出来
8
+ *
9
+ * 主要用于测试框架打印完整的内容
10
+ */
11
+ export function printFormat(params: any) {
12
+ const boolRes = isConditionsSome([
13
+ // 是不是纯对象?
14
+ () => isPlainObject(params),
15
+ // 或者是不是单纯的数组?
16
+ () => isArray(params),
17
+ ]);
18
+
19
+ // 如果是纯对象或者数组,则使用 JSON.stringify 格式化输出 否则原样返回
20
+ const res = boolRes ? JSON.stringify(params, null, 2) : params;
21
+
22
+ return res;
23
+ }
@@ -1 +1,2 @@
1
1
  export * from "./useAxios/index";
2
+ export * from "./useAxios-for-01s/index";
@@ -0,0 +1,4 @@
1
+ export * from "./types/JsonVO";
2
+ export * from "./types/PageDTO";
3
+ export * from "./tools";
4
+ export * from "./main";
@@ -0,0 +1,94 @@
1
+ import type { KeyAxiosRequestConfig, UseAxiosWrapperParams } from "../useAxios/index";
2
+ import { useAxiosWrapper } from "../useAxios/index";
3
+
4
+ import type { UseAxiosOptionsBase } from "@vueuse/integrations/useAxios";
5
+ import type { PartialPick } from "type-plus";
6
+ import type { AxiosInstance } from "axios";
7
+ import axios from "axios";
8
+ import type { JsonVO } from "./types/JsonVO";
9
+
10
+ import type { AxiosRequestConfigBaseKey, HttpParamWay } from "./tools.ts";
11
+ import {
12
+ createDefaultUseAxiosOptions,
13
+ setHeaders,
14
+ UpType,
15
+ setDefaultUseAxiosOptions,
16
+ setDataByHttpParamWay,
17
+ } from "./tools";
18
+
19
+ /**
20
+ * 内部用的 axios 实例
21
+ * @description
22
+ * 主动声明类型 用于约束
23
+ * @private
24
+ */
25
+ let innerAxiosInstance: AxiosInstance = axios;
26
+
27
+ /**
28
+ * 定义具体的 AxiosInstance 实例
29
+ * @description
30
+ * 让外部设置一次内部的默认请求实例
31
+ */
32
+ export function defineAxiosInstance(axiosInstance: AxiosInstance) {
33
+ innerAxiosInstance = axiosInstance;
34
+ }
35
+
36
+ export type ParamsPathKey = AxiosRequestConfigBaseKey | "url";
37
+ export type ParamsQueryKey = AxiosRequestConfigBaseKey | "data";
38
+ export type ParamsBodyKey = AxiosRequestConfigBaseKey | "data";
39
+
40
+ type UseAxiosWrapperUseKey<T extends HttpParamWay, K extends KeyAxiosRequestConfig> =
41
+ //
42
+ T extends HttpParamWay ? Exclude<K, AxiosRequestConfigBaseKey> : never;
43
+
44
+ interface _Params<K extends KeyAxiosRequestConfig, T = any, D = any>
45
+ extends UseAxiosWrapperParams<K, T, UseAxiosOptionsBase<JsonVO<T>>, D> {
46
+ httpParamWay: HttpParamWay;
47
+ upType?: UpType;
48
+ }
49
+
50
+ /** 建议封装接口请求函数不传递 useAxios 的 instance 和 options 参数 */
51
+ type Params<K extends KeyAxiosRequestConfig, T = any, D = any> = PartialPick<_Params<K, T, D>, "instance" | "options">;
52
+
53
+ /**
54
+ * 项目内用的接口请求
55
+ * @description
56
+ * 01s项目内常用的接口请求
57
+ * @version 2
58
+ */
59
+ export function useRequestIn01s<
60
+ K extends KeyAxiosRequestConfig,
61
+ T = any,
62
+ D = any,
63
+ HttpParamWayTemp extends HttpParamWay = Params<K>["httpParamWay"],
64
+ >(
65
+ params: Params<
66
+ //
67
+ UseAxiosWrapperUseKey<HttpParamWayTemp, K>,
68
+ T,
69
+ D
70
+ >,
71
+ ) {
72
+ const {
73
+ config,
74
+ options = createDefaultUseAxiosOptions(),
75
+ instance = innerAxiosInstance,
76
+ httpParamWay,
77
+ upType,
78
+ url,
79
+ } = params;
80
+ setHeaders(config, upType);
81
+ setDefaultUseAxiosOptions(options);
82
+ setDataByHttpParamWay({
83
+ httpParamWay,
84
+ config,
85
+ });
86
+ // console.log(" instance ?", instance.defaults.baseURL);
87
+ return useAxiosWrapper<
88
+ //
89
+ UseAxiosWrapperUseKey<HttpParamWayTemp, K>,
90
+ JsonVO<T>,
91
+ UseAxiosOptionsBase<JsonVO<T>>,
92
+ D
93
+ >({ config, instance, options, url });
94
+ }
@@ -0,0 +1,185 @@
1
+ import type { UseAxiosOptionsBase } from "@vueuse/integrations/useAxios";
2
+ import type { AxiosRequestConfig } from "axios";
3
+
4
+ import { isNil, merge } from "lodash-es";
5
+ import qs from "qs";
6
+
7
+ import type { JsonVO } from "./types/JsonVO";
8
+ import { isConditionsSome } from "../../index";
9
+
10
+ /**
11
+ * http的接口传参方式
12
+ * @description
13
+ * 用于控制接口请求时的参数传递方式
14
+ * @see https://www.cnblogs.com/jinyuanya/p/13934722.html
15
+ */
16
+ export type HttpParamWay =
17
+ // 路径传参
18
+ | "path"
19
+ // query传参
20
+ | "query"
21
+ // body传参
22
+ | "body";
23
+
24
+ /**
25
+ * 基础的 axios.config 必填项字段
26
+ * @description
27
+ * 用于说明axios配置必须传递method字段
28
+ * @version 2
29
+ */
30
+ export type AxiosRequestConfigBaseKey = "method";
31
+
32
+ /**
33
+ * 数据上传数据类型
34
+ * @description
35
+ * 一个标记工具,用来控制上传数据的格式
36
+ *
37
+ * 目前没有发现axios有类似的上传类型声明
38
+ */
39
+ export enum UpType {
40
+ /** 表单类型 */
41
+ form = 0,
42
+
43
+ /** json类型 */
44
+ json = 1,
45
+
46
+ /** 文件类型 */
47
+ file = 3,
48
+
49
+ /** 文件流类型 */
50
+ stream = 4,
51
+ }
52
+
53
+ /**
54
+ * HTTP状态码
55
+ * @description
56
+ * 待优化 未来可以直接复用axios内提供的值 不需要额外地封装工具
57
+ */
58
+ export enum HttpCode {
59
+ /** 暂未登录或TOKEN已经过期 */
60
+ UNAUTHORIZED = 401,
61
+ /** 没有相关权限 */
62
+ FORBIDDEN = 403,
63
+ /** 访问页面未找到 */
64
+ NOT_FOUND = 404,
65
+ /** 服务器错误 */
66
+ SERVER_ERROR = 9994,
67
+ /** 上传参数异常 */
68
+ PARAMS_INVALID = 9995,
69
+ /** ContentType错误 */
70
+ CONTENT_TYPE_ERR = 9996,
71
+ /** 功能尚未实现 */
72
+ API_UN_IMPL = 9997,
73
+ /** 服务器繁忙 */
74
+ SERVER_BUSY = 9998,
75
+ /** 操作失败 */
76
+ FAIL = 9999,
77
+ /** 操作成功 */
78
+ SUCCESS = 10000,
79
+ }
80
+
81
+ /**
82
+ * 上传类型-请求体类型 枚举
83
+ * @description
84
+ * 待优化 未来可以直接复用axios内提供的值 不需要额外地封装工具
85
+ */
86
+ export enum MapContentTypeUpType {
87
+ "application/json;charset=UTF-8" = UpType.json,
88
+ "multipart/form-data" = UpType.file,
89
+ "application/octet-stream" = UpType.stream,
90
+ "application/x-www-form-urlencoded;charset=UTF-8" = UpType.form,
91
+ }
92
+
93
+ /** @private */
94
+ type ContentType = keyof typeof MapContentTypeUpType;
95
+
96
+ /**
97
+ * 根据数据上传类型 重设请求头类型
98
+ * @description
99
+ * 不同的数据上传数据类型 要使用不同的接口请求方式
100
+ *
101
+ * 不再有返回值
102
+ * @version 2
103
+ */
104
+ export function setHeaders(config: AxiosRequestConfig, upType: UpType = UpType.json) {
105
+ const contentType = MapContentTypeUpType[upType] as ContentType;
106
+ if (contentType) {
107
+ config = merge<AxiosRequestConfig, AxiosRequestConfig>(config, {
108
+ headers: {
109
+ "Content-Type": contentType,
110
+ },
111
+ });
112
+ }
113
+ if (!isNil(config.data) && upType === UpType.form) {
114
+ config.data = qs.stringify(config.data, { arrayFormat: "repeat" });
115
+ }
116
+ if (!isNil(config.data) && upType === UpType.file) {
117
+ const formData = new FormData();
118
+ for (const key in config.data) {
119
+ formData.append(key, config.data[key]);
120
+ }
121
+ config.data = formData;
122
+ }
123
+ }
124
+
125
+ /**
126
+ * 提供默认返回值的包装类型
127
+ * @description
128
+ * 预期会在每一个接口的包装函数内使用 用来定义 useAxios 的options参数
129
+ *
130
+ * 该类型应该成为高频使用的工具类型
131
+ *
132
+ * 被设计成一个简单的类型 而不是interface接口
133
+ * @version 2
134
+ */
135
+ export type UseAxiosOptionsJsonVO<T = any> = UseAxiosOptionsBase<JsonVO<T>>;
136
+
137
+ /** useAxios的选项配置 且默认带有immediate属性 不立刻执行 */
138
+ export interface UseAxiosOptionsImmediate<T = any> extends UseAxiosOptionsJsonVO<T> {
139
+ /**
140
+ * @default false
141
+ * @description
142
+ * 默认为 false 不立刻执行
143
+ */
144
+ immediate: boolean;
145
+ }
146
+
147
+ /** 生成默认的选项配置 */
148
+ export function createDefaultUseAxiosOptions<T = any>(): UseAxiosOptionsImmediate<T> {
149
+ return {
150
+ immediate: false,
151
+ };
152
+ }
153
+
154
+ /**
155
+ * 设置默认的 useAxiosOptions 参数值
156
+ * @description
157
+ * 设置 immediate 的值
158
+ *
159
+ * 如果外部没有传递 immediate 属性,那么就使用默认的值
160
+ *
161
+ * 每个业务接口都会传递 options 值,本函数用来完成默认的参数补全。
162
+ */
163
+ export function setDefaultUseAxiosOptions<T>(options: UseAxiosOptionsBase<T>) {
164
+ const _options = createDefaultUseAxiosOptions();
165
+ options.immediate = options?.immediate ?? _options.immediate;
166
+ }
167
+
168
+ /** @private */
169
+ interface SetDataByHttpParamWayParams {
170
+ httpParamWay: HttpParamWay;
171
+ config: AxiosRequestConfig;
172
+ }
173
+ export function setDataByHttpParamWay(params: SetDataByHttpParamWayParams) {
174
+ const { httpParamWay, config } = params;
175
+ if (
176
+ isConditionsSome([
177
+ //
178
+ () => config.method === "GET",
179
+ () => config.method === "get",
180
+ () => httpParamWay === "query",
181
+ ])
182
+ ) {
183
+ config.params = config.data;
184
+ }
185
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * 前后端数据对接数据对象
3
+ * @description
4
+ * 后端 JsonVO 泛型类的前端翻译
5
+ *
6
+ * `01s` 项目统一的数据返回格式
7
+ */
8
+ export interface JsonVO<T> {
9
+ /** 状态码 */
10
+ code: number;
11
+
12
+ /** 提示消息 */
13
+
14
+ message: string;
15
+
16
+ /** 数据对象 */
17
+ data: T;
18
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * 数据分页的返回对象
3
+ * @description
4
+ *
5
+ * `01s` 项目统一的数据返回格式
6
+ */
7
+ export interface PageDTO<T> {
8
+ /**
9
+ * 当前页码
10
+ */
11
+ pageIndex: number;
12
+
13
+ /**
14
+ * 每页显示最大数据条数
15
+ */
16
+
17
+ pageSize: number;
18
+
19
+ /**
20
+ * 总条数
21
+ */
22
+ total: number;
23
+
24
+ /**
25
+ * 总页数
26
+ */
27
+ pages: number;
28
+
29
+ /**
30
+ * 当前页数据列表
31
+ */
32
+ rows: T[];
33
+ }