cg-utils
v0.0.47
Published
This is a simple utility package
Downloads
12
Readme
Installation
Using npm:
$ npm i --save cg-utils
$ pnpm i cg-utils
$ yarn add cg-utils
Usage
全局配置
import {
setUtilsConfig
} from 'cg-utils';
setUtilsConfig({
format: 'YYYY-MM-DD HH:mm:ss', // 设置时间格式
timezone: 'Asia/Shanghai' // 设置时区
})
Mqtt
// 新建一个文件保存以下代码
import {
SocketSingleton
} from 'cg-utils'
/**
* 默认会订阅所有topics
*/
export const connect = () => {
socket = SocketSingleton.getInstance({
servers: [
{
host: 'xxx',
port: 'xxx' as any,
protocol: 'wss'
},
{
host: 'yyy',
port: 'yyy' as any,
protocol: 'wss'
}
],
username: 'username',
password: 'password',
clientId: 'xxxxxxx',
topics: ['topic1', 'topic2'],
})
/**
* 接受消息,不会有重复消息
*/
socket.onMessage = (topic: any, message: any, packet: any) => {
console.log('我是OnMessage', topic, message.toString(), packet)
}
}
// 单独订阅
export const unsubscribe = () => {
socket.unsubscribe('xxx')
}
// 单独取消
export const subscribe = () => {
socket.subscribe('xxx/xxx')
}
// 关闭当前实例,如果需要重新连接,需要重新实例化(SocketSingleton.getInstance())
export const close = () => {
SocketSingleton.close()
}
辅助函数,简化js
extend({a: 1}, {b: 2}) // {a: 1, b: 2}
remove([1, 2, 3], 2) // [1, 3]
isArray([1, 2, 3]) // true
isMap(new Map()) // true
isSet(new Set()) // true
isDate(new Date()) // true
isRegExp(/a/) // true
isFunction(() => {}) // true
isString('a') // true
isNumber(1) // true
isSymbol(Symbol('a')) // true
isObject({a: 1}) // true
isPromise(Promise.resolve()) // true
精度计算
import {
add,
subtract,
multiply,
divide
} from 'cg-utils';
加密功能(xxtea)
import {
setXxetaConfig,
decryptQuery,
getServerTime,
setServerTime
} from 'cg-utils';
/**
* 在axios request拦截器中使用
* requestConfig 是 request拦截器的函数的回调,直接放入就好
* config 配置详情见 cg-utils/index.d.ts
*/
setXxetaConfig(
requestConfig,
config
)
图片兼容性处理
import {
setHtmlPictureCompatilble, // 给html设置class,用于获取支持哪些特殊图片
getPictureSuffix // 获取图片后缀,比如webp,avif,都不匹配返回png
} from 'cg-utils';
获取当前设备信息
/**
* 获取当前设备信息
* @returns {Object} 设备信息
* @property {boolean} isAndroid 是否为安卓设备
* @property {boolean} isIOS 是否为 IOS 设备
* @property {boolean} isMobile 是否为移动设备
* @property {boolean} isWechat 是否为微信浏览器
* @property {boolean} isAlipay 是否为支付宝浏览器
* @property {boolean} isQQ 是否为 QQ 浏览器
* @property {boolean} isBaidu 是否为百度浏览器
* @property {boolean} isSafari 是否为 Safari 浏览器
* @property {boolean} isChrome 是否为 Chrome 浏览器
* @property {boolean} isFirefox 是否为 Firefox 浏览器
* @property {boolean} isEdge 是否为 Edge 浏览器
* @property {boolean} isIE 是否为 IE 浏览器
* @property {boolean} isPC 是否为 PC 设备
* @example getDevice()
*/
import {
getDevice
} from 'cg-utils';
处理html转义符(beta)
escapeHtml('<div>123</div>') // <div>123</div>
unescapeHtml('<div>123</div>') // <div>123</div>
处理加解密(CBOR)
cborEncrypt()
cborDecrypt()
时间戳转日期字符串
timestamp2Date(timestamp,format = utilsConfig.format, timezone = utilsConfig.timezone)
复制功能
copy('Hello World!!')