Commit a5244c0f by liimin

完善功能

1 parent 3ce590a0
{
"name": "glsx-common-sdk",
"version": "0.1.3",
"version": "0.2.0",
"description": "glsx-common-sdk",
"main": "src/index.js",
"scripts": {
......
import { storage } from '../../helper/storage/index'
import { webwx } from '../../helper/index'
import { storediff } 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)
const webwx = {
getResult: data => {
const v = storediff.get(GLSX_COMMON_VERSION_STORAGE_VERSION)
const compare = compareVersions(v, data.version)
return { compare, origin: v, isNew: compare === -1, ...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 }
setVersion: version => {
const v = storediff.get(GLSX_COMMON_VERSION_STORAGE_VERSION)
if(v===version) return
storediff.set(GLSX_COMMON_VERSION_STORAGE_VERSION, version)
}
}
function compare(version1, version2) {
function compareVersions(version1, version2) {
if (!version1) {
return -1
}
......@@ -38,4 +31,5 @@ function compare(version1, version2) {
}
return 0 // version1 == version2
}
export default webwx(web, wx)
export default webwx
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 })
constructor(options = {}) {
this.request = new Request(options)
}
async get(data) {
const versionInfo = await this.request.get(data)
return webwx.getBody(versionInfo)
return webwx.getResult(versionInfo)
}
set(version) {
return webwx.setVersion(version)
......
export const isMiniprogram = !window
export const isMiniprogram = typeof(window)==='undefined'
export const webwx = (wb, wx, isMP = isMiniprogram) => [wb, wx][+isMP]
\ No newline at end of file
......@@ -4,8 +4,9 @@
* @Author: limin
* @Date: 2023-07-04 17:37:45
* @LastEditors: limin
* @LastEditTime: 2023-08-17 19:29:42
* @LastEditTime: 2023-08-18 13:59:12
* @FilePath: \glsx-common-sdk\src\helper\index.js
*/
export { isMiniprogram, webwx } from './f'
export { storage } from './storage/index'
import { isMiniprogram, webwx } from './f'
import { storage, storediff } from './storage/index'
export { isMiniprogram, webwx, storage, storediff }
import storage from './web'
export { storage }
import { isMiniprogram } from '../f'
const storediff = {
get: key => {
// 根据平台选择不同的获取方法
if (isMiniprogram) {
return wx.getStorageSync(key) // 微信小程序平台
} else {
return storage.get(key) // web 平台
}
},
set: (key, value) => {
// 根据平台选择不同的设置方法
if (isMiniprogram) {
wx.setStorage({ key, data: value }) // 微信小程序平台
} else {
storage.set(key, value) // web 平台
}
}
}
export { storage, storediff }
const response = {
data_key: 'data',
message_key: 'message',
code_key: ['code', 'returnCode'],
code_key: 'code',
code_success_value: '0',
errId_logout_value: '21',
logout_function: 'reLogin',
......
import { sha1, md5, qs } from '../lib/index'
import RequestMethods from './requestMethods'
const createSign = 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
}
const webRequest = async ({ method, obj = {}, baseUrl, headers = {} }, returnAll, logoutCallback, alert) => {
let requestAddrss = baseUrl
const settings = {
method
}
if (method.toUpperCase() === RequestMethods.GET) {
const params = []
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()
return responseHandler(data, returnAll, initResponse, alert, logoutCallback)
} catch (error) {
console.error(`接口异常:`, error)
throw error
}
}
const wxRequest = async ({ method, obj = {}, baseUrl }, returnAll, logoutCallback, alert, initResponse) => {
wx.showNavigationBarLoading()
const header = method.toUpperCase() === RequestMethods.POST ? { 'content-type': 'application/json' } : {}
try {
const res = await new Promise((resolve, reject) => {
wx.request({
url: baseUrl,
data: obj,
method,
header,
dataType: 'json',
responseType: 'text',
success: resolve,
fail: reject
})
})
const { statusCode, data, errMsg } = res
if (statusCode == '200') {
return responseHandler(data, returnAll, initResponse, alert, logoutCallback)
}
} catch (error) {
console.error(`接口异常:`, error)
alert('系统异常')
throw error
} finally {
wx.hideNavigationBarLoading()
}
}
function responseHandler(res, returnAll, initResponse, alert, logoutCallback) {
const { code_key, errId, code_success_value, data_key, errId_logout_value, logout_function } = initResponse
let codekey = Array.isArray(code_key) ? code_key.find(key => res.hasOwnProperty(key)) : code_key
let code = res[codekey]
let errValue = res[errId]
const isLogout = (code && code === errId_logout_value) || (errValue && errValue === errId_logout_value)
if (returnAll || !alert) {
if (isLogout) {
logout(logout_function, logoutCallback)
}
return res
}
if (code != code_success_value) {
if (isLogout) {
logout(logout_function, logoutCallback)
} else {
alert && alert(res.message || res.msg || '出错了,请联系管理员')
}
}
return res[data_key]
}
function logout(logout_function, logoutCallback) {
if (logoutCallback) {
logoutCallback()
return
}
if (window) {
if (window[logout_function]) {
window[logout_function](window.location.href)
return
}
window.history.pushState({ page: window.location.href }, '', '/login')
}
}
const curl = ({ data, method, request, headers, noSignAttr, returnAll, logoutCallback, isMiniprogram, alert, initResponse, sign }) => {
// 调用getSign方法,传入请求数据和请求路径,得到签名
const signData = request.isSign ? createSign(Object.assign({}, request.sign, data), request.secret, noSignAttr, request.signWay) : data
const options = {
obj: signData,
method,
baseUrl: request.baseUrl,
headers
}
return [webRequest, wxRequest][isMiniprogram](options, returnAll, logoutCallback, alert, initResponse)
}
export { curl }
......@@ -4,43 +4,35 @@
* @Author: limin
* @Date: 2023-07-04 17:25:31
* @LastEditors: limin
* @LastEditTime: 2023-08-17 15:10:36
* @LastEditTime: 2023-08-18 16:29:02
* @FilePath: \glsx-common-sdk\src\request\index.js
*/
import wxRequest from './wx'
import webRequest from './web'
import createSign from './sign'
import { curl } from './helper'
import RequestMethods from './requestMethods'
import { response as res } from './default'
import { response as res, sign as defaultSign } from './default'
import { isMiniprogram } from '../helper/index'
class Request {
// 构造函数,接收key和secret作为参数,如果没有传入,则使用默认值
constructor({ response = res, request = response, headers = {}, alert, isMP } = {}) {
this.response = response
constructor({ response = {}, request, headers = {}, alert, isMP = isMiniprogram, logoutCallback } = {}) {
this.response = Object.assign({}, res, response)
this.request = request
this.headers = headers
this.alert = alert
this.isMiniprogram = +isMP
this.logoutCallback = logoutCallback
}
/**封装的GET方法 */
get(data, noSignAttr) {
get(data, noSignAttr, returnAll) {
// 调用request方法,传入请求方式为GET,请求路径为method,请求数据为data
return this.fetch({ method: RequestMethods.GET, data, noSignAttr })
return this.fetch({ method: RequestMethods.GET, data, noSignAttr, returnAll })
}
post(data, noSignAttr) {
post(data, noSignAttr, returnAll) {
// 调用request方法,传入请求方式为GET,请求路径为method,请求数据为data
return this.fetch({ method: RequestMethods.POST, data, noSignAttr })
return this.fetch({ method: RequestMethods.POST, data, noSignAttr, returnAll })
}
/**封装的请求方法 */
fetch({ data, noSignAttr = [], method = RequestMethods.POST }) {
// 调用getSign方法,传入请求数据和请求路径,得到签名
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)
fetch({ data, noSignAttr = [], method = RequestMethods.POST, returnAll = false }) {
return curl({ data, method, request: this.request, headers: this.headers, noSignAttr, returnAll, logoutCallback: this.logoutCallback, isMiniprogram: this.isMiniprogram, alert: this.alert, initResponse: this.response })
}
}
export default Request
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 { 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])}`))
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 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: baseUrl,
data: obj,
method,
header,
dataType: 'json',
responseType: 'text',
success: resolve,
fail: reject
})
})
const { statusCode, data, errMsg } = res
if (statusCode == '200') {
if (data.status == '1') {
return data
} else {
wx.showToast({
title: data.info,
icon: 'none'
})
}
} else {
wx.showToast({
title: errMsg,
icon: 'error'
})
}
} catch (error) {
wx.hideLoading()
console.error(`接口异常:`, error)
wx.showToast({
title: '系统异常',
icon: 'error'
})
throw error
} finally {
wx.hideNavigationBarLoading()
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!