ph-utils 0.9.3 → 0.9.5

Sign up to get free protection for your applications and to get access to all the features.
package/lib/file.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * @param defaultValue 文件不存在时默认值, 不传则抛异常, 如果传递的是对象形式则会将结果转换为 JSON
9
9
  * @returns 文件内容
10
10
  */
11
- export declare function read<T>(filepath: string, defaultValue?: T): Promise<any>;
11
+ export declare function read<T>(filepath: string, defaultValue?: T): Promise<T>;
12
12
  /**
13
13
  * 写入 JSON 格式的数据到文件
14
14
  * @param file 待写入的文件
package/lib/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * 验证字符串是否为空
3
- * @param str 待验证的字符串
4
- * @param ignoreWhitespace 是否忽略空格(包括空白字符串以及[\r\t\n]之类的制表符),默认为true
2
+ * 验证参数是否为空
3
+ * @param str 待验证的参数
4
+ * @param ignoreWhitespace 如果是字符串是否忽略空格(包括空白字符串以及[\r\t\n]之类的制表符),默认为true
5
5
  */
6
- export declare function isBlank(str?: string | null, ignoreWhitespace?: boolean): boolean;
6
+ export declare function isBlank(str?: any, ignoreWhitespace?: boolean): boolean;
7
7
  /**
8
8
  * 屏蔽手机号,中间部分用 * 展示
9
9
  * @param mobile 待屏蔽的手机号
@@ -122,4 +122,8 @@ export declare function snakeCaseStyle(name: string, connector?: string): string
122
122
  * @returns 返回经过指定方式舍入后的数字
123
123
  */
124
124
  export declare function round(num: number, precision?: number, roundType?: 0 | 1 | 2): number;
125
+ /**
126
+ * 反转字符串
127
+ */
128
+ export declare function reverseStr(str: string): string;
125
129
  export {};
package/lib/index.js CHANGED
@@ -6,15 +6,17 @@ const RANDOM_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345
6
6
  /** 只包含字母的随机数字符 */
7
7
  const NUMBER_RANDOM_CHARTS = "0123456789";
8
8
  /**
9
- * 验证字符串是否为空
10
- * @param str 待验证的字符串
11
- * @param ignoreWhitespace 是否忽略空格(包括空白字符串以及[\r\t\n]之类的制表符),默认为true
9
+ * 验证参数是否为空
10
+ * @param str 待验证的参数
11
+ * @param ignoreWhitespace 如果是字符串是否忽略空格(包括空白字符串以及[\r\t\n]之类的制表符),默认为true
12
12
  */
13
13
  export function isBlank(str, ignoreWhitespace = true) {
14
14
  if (str == null) {
15
15
  return true;
16
16
  }
17
- return (ignoreWhitespace ? str.trim().length : str.length) === 0;
17
+ return ((ignoreWhitespace && typeof str === "string"
18
+ ? str.trim().length
19
+ : str.length) === 0);
18
20
  }
19
21
  /**
20
22
  * 屏蔽手机号,中间部分用 * 展示
@@ -86,11 +88,6 @@ export function random(opts) {
86
88
  * 带有错误名称标记的错误类型
87
89
  */
88
90
  export class BaseError extends Error {
89
- /**
90
- * 错误名称,类似于 Java 中的不同的 Exception[NullPointerException];
91
- * 增加 name 字段,表明不同的错误,当需要根据不同的错误执行不同的处理的时候,会很有用
92
- */
93
- name;
94
91
  constructor() {
95
92
  if (arguments.length === 1) {
96
93
  super(arguments[0]);
@@ -170,3 +167,9 @@ export function round(num, precision = 2, roundType = 0) {
170
167
  return num;
171
168
  }
172
169
  }
170
+ /**
171
+ * 反转字符串
172
+ */
173
+ export function reverseStr(str) {
174
+ return str.split("").reverse().join("");
175
+ }
package/lib/logger.js CHANGED
@@ -3,17 +3,16 @@ import { format } from "./date";
3
3
  * 日志记录器
4
4
  */
5
5
  export class Logger {
6
- /** 日志级别 */
7
- levels = ["debug", "info", "warn", "error", "fatal"];
8
- colors = {
9
- debug: "#909399",
10
- info: "#1677ff",
11
- warn: "#fadb14",
12
- error: "#eb2f96",
13
- };
14
- option;
15
6
  /** 构造日志记录器 */
16
7
  constructor(option) {
8
+ /** 日志级别 */
9
+ this.levels = ["debug", "info", "warn", "error", "fatal"];
10
+ this.colors = {
11
+ debug: "#909399",
12
+ info: "#1677ff",
13
+ warn: "#fadb14",
14
+ error: "#eb2f96",
15
+ };
17
16
  this.setOption(option || {});
18
17
  }
19
18
  setOption(option) {
package/lib/server.d.ts CHANGED
@@ -8,3 +8,23 @@ import type { SpawnOptions } from "node:child_process";
8
8
  export declare function exec(command: string, args?: string[]): Promise<string>;
9
9
  export declare function exec(command: string, options?: SpawnOptions): Promise<string>;
10
10
  export declare function exec(command: string, args?: string[], options?: SpawnOptions): Promise<string>;
11
+ /**
12
+ * 解析环境变量;
13
+ * 同时读取多个环境变量文件: .env, .env.local, .env.[development|test|production];
14
+ * 根据运行环境变量 `NODE_ENV` 读取不同的环境变量文件;
15
+ * 同时支持手动通过运行命令指定 `NODE_ENV` 值, 不指定默认为: production
16
+ *
17
+ * ```bash
18
+ * node test.js --NODE_ENV development
19
+ * // or
20
+ * node test.js -n development
21
+ * ```
22
+ *
23
+ * ```js
24
+ * // test.js
25
+ * await parseEnvs();
26
+ * ```
27
+ *
28
+ * @returns
29
+ */
30
+ export declare function parseEnvs(): Promise<Record<string, string>>;
package/lib/server.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { parseEnv, parseArgs } from "node:util";
3
+ import { read } from "./file.js";
2
4
  /**
3
5
  * 执行命令
4
6
  * @param cmd 执行的命令
@@ -36,7 +38,7 @@ export function exec(command, ...params) {
36
38
  prs.on("error", (err) => {
37
39
  error = err;
38
40
  });
39
- prs.on("close", (code, signal) => {
41
+ prs.on("close", (code, _signal) => {
40
42
  if (code === 0) {
41
43
  resolve(msg.join("\n"));
42
44
  }
@@ -50,3 +52,56 @@ export function exec(command, ...params) {
50
52
  });
51
53
  });
52
54
  }
55
+ /**
56
+ * 解析环境变量;
57
+ * 同时读取多个环境变量文件: .env, .env.local, .env.[development|test|production];
58
+ * 根据运行环境变量 `NODE_ENV` 读取不同的环境变量文件;
59
+ * 同时支持手动通过运行命令指定 `NODE_ENV` 值, 不指定默认为: production
60
+ *
61
+ * ```bash
62
+ * node test.js --NODE_ENV development
63
+ * // or
64
+ * node test.js -n development
65
+ * ```
66
+ *
67
+ * ```js
68
+ * // test.js
69
+ * await parseEnvs();
70
+ * ```
71
+ *
72
+ * @returns
73
+ */
74
+ export async function parseEnvs() {
75
+ // development, test, production
76
+ const files = [".env", ".env.local"];
77
+ let nodeEnv = process.env.NODE_ENV;
78
+ const { values } = parseArgs({
79
+ options: {
80
+ NODE_ENV: {
81
+ type: "string",
82
+ short: "n",
83
+ },
84
+ },
85
+ });
86
+ if (values.NODE_ENV != null) {
87
+ nodeEnv = values.NODE_ENV;
88
+ }
89
+ else {
90
+ nodeEnv = "production";
91
+ }
92
+ process.env.NODE_ENV = nodeEnv;
93
+ files.push(`.env.${values.NODE_ENV}`);
94
+ let envParsed = {};
95
+ for (let i = 0, len = files.length; i < len; i++) {
96
+ const file = files[i];
97
+ const envContent = await read(file, "");
98
+ if (envContent !== "") {
99
+ const envValue = parseEnv(envContent);
100
+ envParsed = { ...envParsed, ...envValue };
101
+ }
102
+ }
103
+ for (const key in envParsed) {
104
+ process.env[key] = envParsed[key];
105
+ }
106
+ return envParsed;
107
+ }
package/lib/storage.d.ts CHANGED
@@ -13,6 +13,12 @@ interface StorageSetOption {
13
13
  * @param value 设置的值
14
14
  * @param [option.storage] session 或 local, 默认: session
15
15
  * @param [option.expire] 数据有效期, 单位秒, 默认: -1 - 永久存储
16
+ *
17
+ * @example <caption>1. 存储到 SessionStorage</caption>
18
+ * set("key", "value");
19
+ *
20
+ * @example <caption>2. 存储到 LocalStorage</caption>
21
+ * set("key", "value", { storage: "local" });
16
22
  */
17
23
  export declare function set(key: string, value: any, option?: StorageSetOption): void;
18
24
  /**
package/lib/storage.js CHANGED
@@ -7,6 +7,12 @@ function getStorage(storage = "session") {
7
7
  * @param value 设置的值
8
8
  * @param [option.storage] session 或 local, 默认: session
9
9
  * @param [option.expire] 数据有效期, 单位秒, 默认: -1 - 永久存储
10
+ *
11
+ * @example <caption>1. 存储到 SessionStorage</caption>
12
+ * set("key", "value");
13
+ *
14
+ * @example <caption>2. 存储到 LocalStorage</caption>
15
+ * set("key", "value", { storage: "local" });
10
16
  */
11
17
  export function set(key, value, option) {
12
18
  const opts = {
package/lib/theme.d.ts CHANGED
@@ -4,13 +4,13 @@ export declare function getSystemTheme(): "dark" | "light" | "auto";
4
4
  * 初始化主题, 让网页能够适应系统主题, 同时根据缓存的主题切换主题
5
5
  * @returns 当前应用的主题
6
6
  */
7
- export declare function initTheme(): Promise<"dark" | "light" | "auto" | undefined>;
7
+ export declare function initTheme(): Promise<"dark" | "light" | "auto">;
8
8
  /**
9
9
  * 切换主题, 通常用于预览
10
10
  * @param theme 切换的主题
11
11
  * @returns 切换后的主题
12
12
  */
13
- export declare function toggleTheme(theme?: "light" | "dark" | "auto"): Promise<"dark" | "light" | "auto" | undefined>;
13
+ export declare function toggleTheme(theme?: "light" | "dark" | "auto"): Promise<"dark" | "light" | "auto">;
14
14
  /** 获取当前主题 */
15
15
  export declare function getTheme(): string;
16
16
  /**
@@ -19,7 +19,7 @@ export declare function getTheme(): string;
19
19
  * @param cache 是否缓存应用的主题, 让应用下一次启动的时候, 可以应用主题, 默认: true
20
20
  * @returns 应用的主题
21
21
  */
22
- export declare function applyTheme(theme?: "light" | "dark" | "auto", cache?: boolean): Promise<"dark" | "light" | "auto" | undefined>;
22
+ export declare function applyTheme(theme?: "light" | "dark" | "auto", cache?: boolean): Promise<"dark" | "light" | "auto">;
23
23
  /** 获取当前主题色 */
24
24
  export declare function getColorTheme(defaultValue?: string): string | undefined;
25
25
  /**
package/lib/theme.js CHANGED
@@ -37,6 +37,9 @@ export async function initTheme() {
37
37
  */
38
38
  export async function toggleTheme(theme) {
39
39
  const classList = document.documentElement.classList;
40
+ if (theme == null) {
41
+ theme = getSystemTheme();
42
+ }
40
43
  if (theme === "light") {
41
44
  classList.add("light");
42
45
  classList.remove("dark");
@@ -26,7 +26,20 @@ declare class Validator {
26
26
  };
27
27
  /**
28
28
  * 构造数据验证转换器
29
+ *
30
+ * See {@link https://gitee.com/towardly/ph/wikis/utils/validator|Validator文档}.
31
+ *
29
32
  * @param schemas 配置验证转换规则
33
+ *
34
+ * @example
35
+ *
36
+ * const validator = new Validator([
37
+ * { key: 'mobile', rules: ['required', 'mobile'] },
38
+ * { key: 'code': rules: /^\d{6}$/, message: '请输入正确的验证码' },
39
+ * { key: 'confirmPassword', rules: ['required', 'same:password'] }
40
+ * ])
41
+ * // 验证某一个字段
42
+ * validator.validateKey().then(res => {})
30
43
  */
31
44
  constructor(schemas: SchemaType[]);
32
45
  /**
package/lib/validator.js CHANGED
@@ -32,8 +32,6 @@ const ruleFns = {
32
32
  },
33
33
  };
34
34
  class ValidateError extends Error {
35
- name;
36
- key;
37
35
  constructor(key, msg) {
38
36
  super(msg);
39
37
  this.name = "ValidateError";
@@ -44,10 +42,22 @@ class ValidateError extends Error {
44
42
  * 数据验证器
45
43
  */
46
44
  class Validator {
47
- rules;
48
45
  /**
49
46
  * 构造数据验证转换器
47
+ *
48
+ * See {@link https://gitee.com/towardly/ph/wikis/utils/validator|Validator文档}.
49
+ *
50
50
  * @param schemas 配置验证转换规则
51
+ *
52
+ * @example
53
+ *
54
+ * const validator = new Validator([
55
+ * { key: 'mobile', rules: ['required', 'mobile'] },
56
+ * { key: 'code': rules: /^\d{6}$/, message: '请输入正确的验证码' },
57
+ * { key: 'confirmPassword', rules: ['required', 'same:password'] }
58
+ * ])
59
+ * // 验证某一个字段
60
+ * validator.validateKey().then(res => {})
51
61
  */
52
62
  constructor(schemas) {
53
63
  let parsedRules = {};
package/package.json CHANGED
@@ -64,7 +64,7 @@
64
64
  },
65
65
  "./*": "./lib/*"
66
66
  },
67
- "version": "0.9.3",
67
+ "version": "0.9.5",
68
68
  "type": "module",
69
69
  "repository": {
70
70
  "type": "git",