Commit 3ce590a0 by liimin

加入版本比较功能

1 parent 35571c66
module.exports = {
root: true,
env: {
node: true
node: true,
},
parser: '@typescript-eslint/parser',
"parser": "babel-eslint",
parserOptions: {
parser: 'babel-eslint'
ecmaVersion: 7,
sourceType: "module",
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
}
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
},
};
This diff could not be displayed because it is too large.
{
"name": "glsx-common-sdk",
"version": "0.2.0",
"version": "0.1.3",
"description": "glsx-common-sdk",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "rollup -c",
"doc":"jsdoc src/index.js"
"doc": "jsdoc src/index.js"
},
"author": "limin",
"license": "ISC",
"devDependencies": {
"babel-eslint": "^10.1.0",
"rollup": "^1.32.1",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-commonjs": "^10.1.0",
......
import Version from './version'
export { Version }
export const GLSX_COMMON_VERSION_STORAGE_VERSION = 'GLSX_COMMON_VERSION_STORAGE_VERSION'
\ No newline at end of file
import { storage } from '../../helper/storage/index'
import { webwx } from '../../helper/index'
import { GLSX_COMMON_VERSION_STORAGE_VERSION } from './constants'
const web = {
getBody: data => {
const v = storage.get(GLSX_COMMON_VERSION_STORAGE_VERSION)
return result(v, data)
},
setVersion: version => storage.set(GLSX_COMMON_VERSION_STORAGE_VERSION, version)
}
const wx = {
getBody: data => {
const v = wx.getStorageSync(GLSX_COMMON_VERSION_STORAGE_VERSION)
return result(v, data)
},
setVersion: version => wx.setStorage({ key: GLSX_COMMON_VERSION_STORAGE_VERSION, data: version })
}
function result(v, data) {
const c = compare(v, data.version)
return { compare: c, origin: v, new: data.version, isNew: c === -1 ? true : false, ...data }
}
function compare(version1, version2) {
if (!version1) {
return -1
}
const parts1 = version1.split('.')
const parts2 = version2.split('.')
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const part1 = parseInt(parts1[i] || 0)
const part2 = parseInt(parts2[i] || 0)
if (part1 < part2) {
return -1 // version1 < version2
}
if (part1 > part2) {
return 1 // version1 > version2
}
}
return 0 // version1 == version2
}
export default webwx(web, wx)
import Request from '../../request/index'
import webwx from './helper'
import { isMiniprogram } from '../../helper/index'
class Version {
constructor({ http, isMP = isMiniprogram, alert } = {}) {
this.request = new Request({ ...http, isMP, alert })
}
async get(data) {
const versionInfo = await this.request.get(data)
return webwx.getBody(versionInfo)
}
set(version) {
return webwx.setVersion(version)
}
}
export default Version
......@@ -4,7 +4,7 @@
* @Author: limin
* @Date: 2023-07-04 17:40:51
* @LastEditors: limin
* @LastEditTime: 2023-07-05 08:48:32
* @FilePath: \glsx-map-sdk\src\constants.js
* @LastEditTime: 2023-08-16 14:18:31
* @FilePath: \glsx-common-sdk\src\helper\constants.js
*/
export const MAP_OPTIONS = { domain: 'https://restapi.amap.com', KEY: '373bd88fa36ebc0247d60281386b6cec', SECRET: 'a2a93fa04721a36819d86b71cb31fe41' }
export const REQUEST_OPTIONS = { BASE_URL: 'https://restapi.amap.com', APP_KEY: '373bd88fa36ebc0247d60281386b6cec', SECRET: 'a2a93fa04721a36819d86b71cb31fe41' }
export const isMiniprogram = !window
export const webwx = (wb, wx, isMP = isMiniprogram) => [wb, wx][+isMP]
\ No newline at end of file
......@@ -4,7 +4,8 @@
* @Author: limin
* @Date: 2023-07-04 17:37:45
* @LastEditors: limin
* @LastEditTime: 2023-07-05 08:46:52
* @FilePath: \glsx-map-sdk\src\helper.js
* @LastEditTime: 2023-08-17 19:29:42
* @FilePath: \glsx-common-sdk\src\helper\index.js
*/
export const isMiniprogram = !window
export { isMiniprogram, webwx } from './f'
export { storage } from './storage/index'
import storage from './web'
export { storage }
/*
* @Author: limin
* @Date: 2018-06-23 11:13:44
* @Last Modified by: limin
* @Last Modified time: 2018-08-31 18:28:26
*/
const TYPE = {
LOCAL: 'localStorage',
SESSION: 'sessionStorage'
}
function isObject(val) {
return val !== null && typeof val === 'object'
}
function encrypt(val) {
if (!val) return val
return val
}
function decrypt(val) {
if (!val) return val
return val
}
function set(key, val, type = TYPE.LOCAL) {
if (isObject(val)) window[type].setItem(key, JSON.stringify(val))
else window[type].setItem(key, encrypt(val))
}
function get(key, type = TYPE.LOCAL) {
var val = window[type].getItem(key)
try {
if (val && val.startsWith('#')) {
return val
}
const value = isObject(val)?JSON.parse(decrypt(val)):decrypt(val)
return value
} catch (e) {
throw e
}
}
function remove(key, type = TYPE.LOCAL) {
window[type].removeItem(key)
}
function setSession(key, val, ex = 20) {
set(key, val, TYPE.SESSION)
}
function getSession(key) {
return get(key, TYPE.SESSION)
}
function removeSession(key) {
remove(key, TYPE.SESSION)
}
// 默认30minute
function setExpire(key, val, ex = 1.8e6) {
set(key, { v: val, t: Date.now() + ex })
}
function getExpire(key) {
var obj = get(key)
if (obj.t > Date.now()) return obj.v
else return null
}
export default {
set,
get,
remove,
setSession,
getSession,
removeSession,
setExpire,
getExpire
}
\ No newline at end of file
File mode changed
/*
* @Descripttion:
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2023-08-15 16:37:55
* @LastEditors: limin
* @LastEditTime: 2023-08-15 18:21:22
* @LastEditTime: 2023-08-17 15:22:04
* @FilePath: \glsx-common-sdk\src\index.js
*/
import Request from './request/index'
class GLCommon {
constructor(params = {}) {
const { key, secret } = params
this.request = new Request(key, secret)
}
}
export default GLCommon
export { Version } from './function/index'
import md5 from './md5'
import sha1 from './sha1'
import qs from './qs'
export { md5, sha1, qs }
(function() {
var crypt = require('crypt'),
utf8 = require('charenc').utf8,
bin = require('charenc').bin,
// The core
sha1 = function (message) {
// Convert to byte array
if (message.constructor == String)
message = utf8.stringToBytes(message);
else if (typeof Buffer !== 'undefined' && typeof Buffer.isBuffer == 'function' && Buffer.isBuffer(message))
message = Array.prototype.slice.call(message, 0);
else if (!Array.isArray(message))
message = message.toString();
// otherwise assume byte array
var m = crypt.bytesToWords(message),
l = message.length * 8,
w = [],
H0 = 1732584193,
H1 = -271733879,
H2 = -1732584194,
H3 = 271733878,
H4 = -1009589776;
// Padding
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >>> 9) << 4) + 15] = l;
for (var i = 0; i < m.length; i += 16) {
var a = H0,
b = H1,
c = H2,
d = H3,
e = H4;
for (var j = 0; j < 80; j++) {
if (j < 16)
w[j] = m[i + j];
else {
var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16];
w[j] = (n << 1) | (n >>> 31);
}
var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
(H1 ^ H2 ^ H3) - 899497514);
H4 = H3;
H3 = H2;
H2 = (H1 << 30) | (H1 >>> 2);
H1 = H0;
H0 = t;
}
H0 += a;
H1 += b;
H2 += c;
H3 += d;
H4 += e;
}
return [H0, H1, H2, H3, H4];
},
// Public API
api = function (message, options) {
var digestbytes = crypt.wordsToBytes(sha1(message));
return options && options.asBytes ? digestbytes :
options && options.asString ? bin.bytesToString(digestbytes) :
crypt.bytesToHex(digestbytes);
};
api._blocksize = 16;
api._digestsize = 20;
module.exports = api;
})();
\ No newline at end of file
const response = {
data_key: 'data',
message_key: 'message',
code_key: ['code', 'returnCode'],
code_success_value: '0',
errId_logout_value: '21',
logout_function: 'reLogin',
code_message_map: {}
}
const request = {
baseURL: '',
// 设置超时时间
timeout: 180000,
// 携带凭证
withCredentials: true,
// 返回数据类型
responseType: 'json'
}
const sign = {
appKey: '48e5e13229b82c1b4e6e8c96151f0637',
v: '1.0.0',
format: 'json',
source: 'scrm',
locale: 'zh_CN',
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
}
export { response, request, sign }
/*
* @Descripttion: 定义一个Request类,用于封装请求高德地图API的方法
* @version: 1.0.0
* @Author: limin
* @Date: 2023-07-04 17:25:31
* @LastEditors: limin
* @LastEditTime: 2023-08-15 18:10:22
* @LastEditTime: 2023-08-17 15:10:36
* @FilePath: \glsx-common-sdk\src\request\index.js
*/
import md5 from '../lib/md5'
import qs from '../lib/qs'
import wxRequest from './wx'
import webRequest from './web'
import { isMiniprogram } from '../helper/index'
import createSign from './sign'
import RequestMethods from './requestMethods'
import { response as res } from './default'
class Request {
// 构造函数,接收key和secret作为参数,如果没有传入,则使用默认值
constructor(key = MAP_OPTIONS.KEY, secret = MAP_OPTIONS.SECRET) {
// 将key和secret赋值给实例属性
this.key = key
this.secret = secret
}
/**对参数进行排序:按参数名升序 */
setLocaleCompare(params) {
// 将key添加到参数对象中
params.key = this.key
return Object.fromEntries(Object.entries(params).sort(([a], [b]) => a.localeCompare(b)))
}
/**签名计算(sig) */
getSign(params) {
return md5(`${decodeURIComponent(qs.stringify(this.setLocaleCompare(params)))}${this.secret}`)
constructor({ response = res, request = response, headers = {}, alert, isMP } = {}) {
this.response = response
this.request = request
this.headers = headers
this.alert = alert
this.isMiniprogram = +isMP
}
/**封装的GET方法 */
get(method, data) {
get(data, noSignAttr) {
// 调用request方法,传入请求方式为GET,请求路径为method,请求数据为data
return this.fetch({ method: RequestMethods.GET, data, noSignAttr })
}
post(data, noSignAttr) {
// 调用request方法,传入请求方式为GET,请求路径为method,请求数据为data
return this.request('GET', method, data)
return this.fetch({ method: RequestMethods.POST, data, noSignAttr })
}
/**封装的请求方法 */
async request(RequestMethods, method, data = {}) {
fetch({ data, noSignAttr = [], method = RequestMethods.POST }) {
// 调用getSign方法,传入请求数据和请求路径,得到签名
const sig = this.getSign(data, method),
obj = {
...this.setLocaleCompare(data),
sig
}
return await [webRequest,wxRequest][+isMiniprogram](RequestMethods, method, obj)
const signData = createSign(data, this.request.secret, noSignAttr, this.request.signWay)
const options = {
obj: signData,
method,
baseUrl: this.request.baseUrl,
headers: this.headers
}
return [webRequest, wxRequest][this.isMiniprogram](options)
}
}
export default Request
export default {
GET: 'GET',
POST: 'POST'
}
\ No newline at end of file
import { sha1, md5, qs } from '../lib/index'
export default function (params, secret, noSignAttr = [], way = 'sha1') {
delete params.sign
params.timestamp = new Date().getTime()
var strQs = qs.stringify(params, { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true })
const objQs = strQs.split('&')
const collect = objQs.reduce((collect, item) => {
const [key, value] = item.split('=')
if (value === null) {
value = ''
} else if (typeof value === 'object') {
value = JSON.stringify(value)
}
collect[key] = decodeURIComponent(value)
return collect
}, {})
const keys = Object.keys(collect).sort()
const str = keys.reduce((col, key) => {
if (!noSignAttr.includes(key)) {
col.push(key, collect[key])
}
return col
}, [])
collect.sign = { sha1, md5 }[way](secret + str.join('') + secret).toUpperCase()
return collect
}
import { MAP_OPTIONS } from '../helper/constants'
export default async (RequestMethods, method, obj = {}) => {
import { qs } from '../lib/index'
import { response } from './default'
import RequestMethods from './requestMethods'
export default async ({ method, obj = {}, baseUrl, headers = {} }) => {
let requestAddrss = baseUrl
const settings = {
method
}
if (method.toUpperCase() === RequestMethods.GET) {
const params = []
Object.keys(obj).map(key => {
params.push(`${key}=${encodeURIComponent(obj[key])}`)
})
try {
const res = await window.fetch(`${MAP_OPTIONS.domain}${method}?${params.join('&')}`, {
method: RequestMethods
})
const data = await res.json()
if (data.status == '1') return data
else throw data.info
} catch (error) {
console.error(`接口异常:`, error)
throw error
}
Object.keys(obj).map(key => params.push(`${key}=${encodeURIComponent(obj[key])}`))
requestAddrss = `${baseUrl}?${params.join('&')}`
settings.headers = headers
} else {
settings.headers = Object.assign({ 'Content-Type': 'application/json' }, headers)
settings.body = qs.stringify(obj)
}
try {
const res = await window.fetch(requestAddrss, settings)
const data = await res.json()
if (data.code == '0') return data.data
else throw data.info
} catch (error) {
console.error(`接口异常:`, error)
throw error
}
}
import { MAP_OPTIONS } from '../helper/constants'
export default async (RequestMethods, method, params = {}) => {
import RequestMethods from './requestMethods'
export default async ({ method, obj = {}, baseUrl }) => {
wx.showNavigationBarLoading()
const header = method.toUpperCase() === RequestMethods.POST ? { 'content-type': 'application/json' } : {}
try {
const res = await new Promise((resolve, reject) => {
wx.request({
url: `${MAP_OPTIONS.domain}${method}`,
data:params,
method: RequestMethods,
header:
RequestMethods === 'POST'
? {
'content-type': 'application/json'
}
: {},
url: baseUrl,
data: obj,
method,
header,
dataType: 'json',
responseType: 'text',
success: resolve,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!