@vtj/utils 0.0.5

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/src/storage.ts ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * 缓存操作模块,提供sessionStorage和localStorage操作
3
+ * @module storage
4
+ * @author 陈华春
5
+ */
6
+
7
+ /**
8
+ * sessionStorage
9
+ * @const
10
+ * @type {Storage}
11
+ */
12
+ const SESSION = window.sessionStorage || {};
13
+
14
+ /**
15
+ * localStorage
16
+ * @type {Storage}
17
+ */
18
+ const LOCAL = window.localStorage || {};
19
+
20
+ /**
21
+ * 内存缓存
22
+ * @type {{}}
23
+ */
24
+ let CACHES: Record<string, any> = {};
25
+
26
+ /**
27
+ * 存储方式映射
28
+ */
29
+ const TYPES: Record<string, any> = {
30
+ local: LOCAL,
31
+ session: SESSION,
32
+ cache: CACHES
33
+ };
34
+
35
+ const defaultOptions = {
36
+ type: 'cache',
37
+ expired: 0,
38
+ prefix: '__NewPearl__'
39
+ };
40
+
41
+ /**
42
+ * 保存缓存
43
+ * @param {string} key 缓存key
44
+ * @param {String|Object|Array} value 缓存值,对象、数组类型自动JSON.stringify成字符串
45
+ * @param {object} [opts] 选项
46
+ * @param {Object} [opts.type=cache] 存储方式 local、 session、cache
47
+ * @param {number} [opts.expired=0] 过期时间,单位毫秒
48
+ * @param {string} [opts.prefix=__NewPearl__] key 前缀
49
+ */
50
+ export function save(key: string, value: any = '', opts = {}) {
51
+ if (!key) return;
52
+ const { type, expired, prefix } = { ...defaultOptions, ...opts };
53
+ const timestamp = Date.now();
54
+ const realKey = prefix + key;
55
+ const storage = TYPES[type] || CACHES;
56
+ const info = {
57
+ value,
58
+ timestamp,
59
+ expired
60
+ };
61
+ if (storage === CACHES) {
62
+ storage[realKey] = info;
63
+ } else {
64
+ storage.setItem(realKey, JSON.stringify(info));
65
+ }
66
+ }
67
+
68
+ /**
69
+ * 获取缓存
70
+ * @param {string} key 缓存key
71
+ * @param {object} [opts] 选项
72
+ * @param {Object} [opts.type=cache] 存储方式 local、 session、cache
73
+ * @param {number} [opts.expired=0] 过期时间,单位毫秒
74
+ * @param {string} [opts.prefix=__NewPearl__] key 前缀
75
+ * @returns {String|Object|Array}
76
+ */
77
+ export function get(key: string, opts = {}) {
78
+ if (!key) return;
79
+ const { type, prefix } = { ...defaultOptions, ...opts };
80
+ const realKey = prefix + key;
81
+ const storage = TYPES[type] || CACHES;
82
+ let info;
83
+ if (storage === CACHES) {
84
+ info = storage[realKey];
85
+ } else {
86
+ const content = storage.getItem(realKey);
87
+ if (content) {
88
+ info = JSON.parse(content);
89
+ }
90
+ }
91
+ // 不存在缓存
92
+ if (!info) return null;
93
+ const { value, timestamp, expired } = info;
94
+ // 缓存是否过期
95
+ const isExpired = expired > 0 && timestamp + expired < Date.now();
96
+ // 过期清空缓存,返回null
97
+ if (isExpired) {
98
+ remove(key, opts);
99
+ return null;
100
+ }
101
+ return value;
102
+ }
103
+
104
+ /**
105
+ * 删除缓存
106
+ * @param {string} key 缓存key
107
+ * @param {object} [opts] 选项
108
+ * @param {Object} [opts.type=cache] 存储方式 local、 session、cache
109
+ * @param {string} [opts.prefix=__NewPearl__] key 前缀
110
+ */
111
+ export function remove(key: string, opts = {}) {
112
+ if (!key) return;
113
+ const { type, prefix } = { ...defaultOptions, ...opts };
114
+ const storage = TYPES[type] || CACHES;
115
+ const realKey = prefix + key;
116
+ if (storage === CACHES) {
117
+ delete storage[realKey];
118
+ } else {
119
+ storage.removeItem(realKey);
120
+ }
121
+ }
122
+
123
+ /**
124
+ * 删除全部缓存
125
+ * @param {object} [opts] 选项
126
+ * @param {Object} [opts.type=cache] 存储方式 local、 session、cache
127
+ */
128
+ export function clear(opts = {}) {
129
+ const { type } = { ...defaultOptions, ...opts };
130
+ const storage = TYPES[type] || CACHES;
131
+ if (storage === CACHES) {
132
+ CACHES = {};
133
+ } else {
134
+ storage.clear();
135
+ }
136
+ }
137
+
138
+ export default {
139
+ save,
140
+ get,
141
+ remove,
142
+ clear
143
+ };
package/src/url.ts ADDED
@@ -0,0 +1,102 @@
1
+ export const UrlRegex = /^(http|https):\/\/[\w.:\-@]*/;
2
+
3
+ export function isUrl(txt: string) {
4
+ return UrlRegex.test(txt);
5
+ }
6
+
7
+ /**
8
+ * 获取当前页面的 host
9
+ * @param {boolean} includePath 带上 pathname
10
+ * @return {string}
11
+ */
12
+ export function getCurrentHost(includePath: boolean) {
13
+ const { protocol, host, pathname } = location;
14
+ return `${protocol}//${host}${includePath ? pathname : ''}`;
15
+ }
16
+
17
+ /**
18
+ * 获取指定url的host
19
+ * @param {string} url
20
+ * @return {string} host
21
+ */
22
+ export function getHost(url: string = '') {
23
+ const matches = url.match(UrlRegex);
24
+ if (matches) {
25
+ return matches[0];
26
+ }
27
+ return '';
28
+ }
29
+
30
+ /**
31
+ * 键值对转换成查询字符串
32
+ * @param {object} query 键值对,对象
33
+ * @returns {string} 查询参数字符串
34
+ */
35
+ export function stringify(query: Record<string, any>) {
36
+ const array = [];
37
+ for (const key in query) {
38
+ if (Object.prototype.hasOwnProperty.call(query, key)) {
39
+ array.push([key, encodeURIComponent(query[key])].join('='));
40
+ }
41
+ }
42
+ return array.join('&');
43
+ }
44
+
45
+ /**
46
+ * 参数字符串转换成对象形式,如:a=1&b=2 转换成 {a:1, b:2}
47
+ * @param {String} str 需要转换的字符串
48
+ * @param {String} [sep=&] 连接符,可选,默认 &
49
+ * @param {String} [eq==] 键值间隔符,可选,默认 =
50
+ * @returns {Object}
51
+ */
52
+ export function parse(str: string, sep?: string, eq?: string) {
53
+ const obj: Record<string, any> = {};
54
+ str = (str || location.search).replace(/^[^]*\?/, '');
55
+ sep = sep || '&';
56
+ eq = eq || '=';
57
+ let arr;
58
+ const reg = new RegExp(
59
+ '(?:^|\\' +
60
+ sep +
61
+ ')([^\\' +
62
+ eq +
63
+ '\\' +
64
+ sep +
65
+ ']+)(?:\\' +
66
+ eq +
67
+ '([^\\' +
68
+ sep +
69
+ ']*))?',
70
+ 'g'
71
+ );
72
+ while ((arr = reg.exec(str)) !== null) {
73
+ if (arr[1] !== str) {
74
+ obj[decodeURIComponent(arr[1])] = decodeURIComponent(arr[2] || '');
75
+ }
76
+ }
77
+ return obj;
78
+ }
79
+
80
+ /**
81
+ * 在url追加参数
82
+ * @param {string} url 原本的url
83
+ * @param {string|object} query 需要追加的参数,Object|String
84
+ * @returns {string} 追加参数后的url
85
+ */
86
+ export function append(url: string, query: string | Record<string, any>) {
87
+ query = typeof query === 'string' ? parse(query) : query;
88
+ const path = url.split('?')[0];
89
+ const originalQuery = parse(url);
90
+ const joinQuery = Object.assign({}, originalQuery, query);
91
+ const queryStr = stringify(joinQuery);
92
+ return queryStr ? [path, queryStr].join('?') : url;
93
+ }
94
+
95
+ export default {
96
+ isUrl,
97
+ getCurrentHost,
98
+ getHost,
99
+ stringify,
100
+ parse,
101
+ append
102
+ };
package/src/util.ts ADDED
@@ -0,0 +1,74 @@
1
+ export {
2
+ get,
3
+ set,
4
+ isPlainObject,
5
+ cloneDeep,
6
+ merge,
7
+ debounce,
8
+ throttle,
9
+ isEqual
10
+ } from 'lodash-es';
11
+
12
+ export function uid() {
13
+ return Number(Math.random().toString().substring(2, 5) + Date.now()).toString(
14
+ 36
15
+ );
16
+ }
17
+
18
+ export function isFunction(val: any): boolean {
19
+ return typeof val === 'function';
20
+ }
21
+
22
+ /**
23
+ * 提取对象属性
24
+ * @param object
25
+ * @param filter
26
+ * @returns
27
+ */
28
+ export function pick(
29
+ object: Record<string, any>,
30
+ filter?: (v: any) => boolean
31
+ ) {
32
+ const obj: Record<string, any> = Object.create(null);
33
+ const match = filter || ((v) => v !== null && v !== undefined);
34
+ Object.entries(object).forEach(([n, v]) => {
35
+ if (match(v)) {
36
+ obj[n] = v;
37
+ }
38
+ });
39
+ return obj;
40
+ }
41
+
42
+ /**
43
+ * 递归对象或数组清除文本类型值的两边空格
44
+ * @param {Object|Array} obj
45
+ * @return {Object|Array}
46
+ */
47
+ export function trim(obj: any): any {
48
+ const type = typeof obj;
49
+ if (type === 'string') {
50
+ return obj.trim();
51
+ }
52
+ if (Array.isArray(obj)) {
53
+ return obj.map((n: any) => trim(n));
54
+ }
55
+ if (obj && type === 'object') {
56
+ Object.entries(obj).forEach(([k, v]) => {
57
+ obj[k] = trim(v);
58
+ });
59
+ return obj;
60
+ }
61
+ return obj;
62
+ }
63
+
64
+ /**
65
+ * 截取几位小数
66
+ * @param {number} value 浮点数
67
+ * @param {number} [number=2] 保留几位小数
68
+ * @param {boolean} [round] 是否四舍五入
69
+ * @returns {number}
70
+ */
71
+ export function toFixed(value: number, number = 2, round: boolean) {
72
+ const method = round ? Math.round : Math.floor;
73
+ return method(Math.pow(10, number) * value) / Math.pow(10, number);
74
+ }
@@ -0,0 +1,7 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ declare module '*.vue' {
4
+ import type { DefineComponent } from 'vue';
5
+ const component: DefineComponent<{}, {}, any>;
6
+ export default component;
7
+ }
@@ -0,0 +1,4 @@
1
+ declare module '@vtj/utils' {
2
+ //@ts-ignore
3
+ export * from '@vtj/utils/types/src/index';
4
+ }
@@ -0,0 +1,2 @@
1
+ import axios from 'axios';
2
+ export { axios };
@@ -0,0 +1,10 @@
1
+ export interface ICookieOptions {
2
+ expires?: number;
3
+ path?: string;
4
+ domain?: string;
5
+ secure?: boolean;
6
+ sameSite?: string;
7
+ }
8
+ export declare function set(name: string, value: string, opts?: ICookieOptions): void;
9
+ export declare function get(name: string): string | undefined;
10
+ export declare function remove(name: string, opts?: ICookieOptions): void;
@@ -0,0 +1 @@
1
+ export declare function md5(content: string): string;
@@ -0,0 +1,2 @@
1
+ import * as dayjs from 'dayjs';
2
+ export { dayjs };
@@ -0,0 +1,8 @@
1
+ export * from './util';
2
+ export * from './axios';
3
+ export * from './request';
4
+ export * as cookie from './cookie';
5
+ export * as storage from './storage';
6
+ export * as crypto from './crypto';
7
+ export * as url from './url';
8
+ export { dayjs } from './dayjs';
@@ -0,0 +1,41 @@
1
+ declare const instance: import("axios").AxiosInstance;
2
+ export interface ISettings {
3
+ loading?: boolean;
4
+ showLoading?: () => void;
5
+ hideLoading?: () => void;
6
+ loadingTime?: 200;
7
+ type?: 'form' | 'json' | 'data';
8
+ originResponse?: boolean;
9
+ validSuccess?: boolean;
10
+ validate?: (res: any) => boolean;
11
+ failMessage?: boolean;
12
+ showError?: (msg: any) => void;
13
+ injectHeaders?: (options: IOptions) => Record<string, string>;
14
+ defaults?: Record<string, any>;
15
+ trim?: boolean;
16
+ picked?: boolean;
17
+ pickFilter?: (v: any) => boolean;
18
+ skipWarnResponseCode?: number;
19
+ skipWarnExecutor?: () => void;
20
+ skipWarnCallback?: () => void;
21
+ skipWarnFinally?: () => void;
22
+ skipWarn?: boolean;
23
+ }
24
+ declare const __settings__: ISettings;
25
+ export declare function setConfig(config: ISettings): void;
26
+ export interface IOptions {
27
+ url: string;
28
+ method?: 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH';
29
+ baseURL?: string;
30
+ headers?: Record<string, string>;
31
+ params?: any;
32
+ data?: any;
33
+ timeout?: number;
34
+ settings?: ISettings;
35
+ }
36
+ export declare type IApiOptions = string | IOptions;
37
+ declare function request(options: IOptions, currentSettings?: ISettings): Promise<unknown>;
38
+ export declare function createApi(options: IApiOptions): (data: any, currentOptions?: {}) => Promise<unknown>;
39
+ export declare function setRequest(success: any, fail?: any): any;
40
+ export declare function setResponse(success: any, fail?: any): any;
41
+ export { request, instance as axiosInstance, __settings__ as RequestSettings };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * 缓存操作模块,提供sessionStorage和localStorage操作
3
+ * @module storage
4
+ * @author 陈华春
5
+ */
6
+ /**
7
+ * 保存缓存
8
+ * @param {string} key 缓存key
9
+ * @param {String|Object|Array} value 缓存值,对象、数组类型自动JSON.stringify成字符串
10
+ * @param {object} [opts] 选项
11
+ * @param {Object} [opts.type=cache] 存储方式 local、 session、cache
12
+ * @param {number} [opts.expired=0] 过期时间,单位毫秒
13
+ * @param {string} [opts.prefix=__NewPearl__] key 前缀
14
+ */
15
+ export declare function save(key: string, value?: any, opts?: {}): void;
16
+ /**
17
+ * 获取缓存
18
+ * @param {string} key 缓存key
19
+ * @param {object} [opts] 选项
20
+ * @param {Object} [opts.type=cache] 存储方式 local、 session、cache
21
+ * @param {number} [opts.expired=0] 过期时间,单位毫秒
22
+ * @param {string} [opts.prefix=__NewPearl__] key 前缀
23
+ * @returns {String|Object|Array}
24
+ */
25
+ export declare function get(key: string, opts?: {}): any;
26
+ /**
27
+ * 删除缓存
28
+ * @param {string} key 缓存key
29
+ * @param {object} [opts] 选项
30
+ * @param {Object} [opts.type=cache] 存储方式 local、 session、cache
31
+ * @param {string} [opts.prefix=__NewPearl__] key 前缀
32
+ */
33
+ export declare function remove(key: string, opts?: {}): void;
34
+ /**
35
+ * 删除全部缓存
36
+ * @param {object} [opts] 选项
37
+ * @param {Object} [opts.type=cache] 存储方式 local、 session、cache
38
+ */
39
+ export declare function clear(opts?: {}): void;
40
+ declare const _default: {
41
+ save: typeof save;
42
+ get: typeof get;
43
+ remove: typeof remove;
44
+ clear: typeof clear;
45
+ };
46
+ export default _default;
@@ -0,0 +1,44 @@
1
+ export declare const UrlRegex: RegExp;
2
+ export declare function isUrl(txt: string): boolean;
3
+ /**
4
+ * 获取当前页面的 host
5
+ * @param {boolean} includePath 带上 pathname
6
+ * @return {string}
7
+ */
8
+ export declare function getCurrentHost(includePath: boolean): string;
9
+ /**
10
+ * 获取指定url的host
11
+ * @param {string} url
12
+ * @return {string} host
13
+ */
14
+ export declare function getHost(url?: string): string;
15
+ /**
16
+ * 键值对转换成查询字符串
17
+ * @param {object} query 键值对,对象
18
+ * @returns {string} 查询参数字符串
19
+ */
20
+ export declare function stringify(query: Record<string, any>): string;
21
+ /**
22
+ * 参数字符串转换成对象形式,如:a=1&b=2 转换成 {a:1, b:2}
23
+ * @param {String} str 需要转换的字符串
24
+ * @param {String} [sep=&] 连接符,可选,默认 &
25
+ * @param {String} [eq==] 键值间隔符,可选,默认 =
26
+ * @returns {Object}
27
+ */
28
+ export declare function parse(str: string, sep?: string, eq?: string): Record<string, any>;
29
+ /**
30
+ * 在url追加参数
31
+ * @param {string} url 原本的url
32
+ * @param {string|object} query 需要追加的参数,Object|String
33
+ * @returns {string} 追加参数后的url
34
+ */
35
+ export declare function append(url: string, query: string | Record<string, any>): string;
36
+ declare const _default: {
37
+ isUrl: typeof isUrl;
38
+ getCurrentHost: typeof getCurrentHost;
39
+ getHost: typeof getHost;
40
+ stringify: typeof stringify;
41
+ parse: typeof parse;
42
+ append: typeof append;
43
+ };
44
+ export default _default;
@@ -0,0 +1,24 @@
1
+ export { get, set, isPlainObject, cloneDeep, merge, debounce, throttle, isEqual } from 'lodash-es';
2
+ export declare function uid(): string;
3
+ export declare function isFunction(val: any): boolean;
4
+ /**
5
+ * 提取对象属性
6
+ * @param object
7
+ * @param filter
8
+ * @returns
9
+ */
10
+ export declare function pick(object: Record<string, any>, filter?: (v: any) => boolean): Record<string, any>;
11
+ /**
12
+ * 递归对象或数组清除文本类型值的两边空格
13
+ * @param {Object|Array} obj
14
+ * @return {Object|Array}
15
+ */
16
+ export declare function trim(obj: any): any;
17
+ /**
18
+ * 截取几位小数
19
+ * @param {number} value 浮点数
20
+ * @param {number} [number=2] 保留几位小数
21
+ * @param {boolean} [round] 是否四舍五入
22
+ * @returns {number}
23
+ */
24
+ export declare function toFixed(value: number, number: number | undefined, round: boolean): number;
@@ -0,0 +1,3 @@
1
+ export { get, set, isPlainObject, cloneDeep, merge, debounce, throttle, isEqual } from 'lodash-es';
2
+ export declare function uid(): string;
3
+ export declare function isFunction(val: any): boolean;