data-utils.js
3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import uuid from '../vendors/uuid'
export default {
globalData: {},
config: {},
setApp(app) {
this.globalData = app.globalData;
},
setConfig(data) {
this.setGlobalData('config', data)
},
getConfig() {
return this.getGlobalDataByKey('config')
},
getStorageSync(key,fromPage = 'app') {
try {
var value = wx.getStorageSync(key)
if (value) {
return value
}
} catch (e) {
wx.reportAnalytics('get_storage_error', {
key: key,
error: e.message,
error_code: e.code,
from_page: fromPage,
});
console.log(`wx.getStorageSync get ${key} failed.`)
return null;
}
},
removeStorageSync(key) {
try {
wx.removeStorageSync(key)
} catch (e) {
console.log(`wx.removeStorageSync del ${key} failed.`)
}
},
clearUserSession(arr) {
const clearKeys = [
'userInfo',
...arr
];
clearKeys.forEach(key => {
this.globalData[key] && this.setGlobalData(key,'')
});
},
/**
* 按变量名存储数据到globalData及缓存
* @param name string
* @param data string / object
* @param isStorage Boolean
*/
setGlobalData(name, data, isStorage = true) {
if (typeof data === 'object' && Object.keys(data).length !== 0) {
this.globalData[name] = {...this.globalData[name], ...data}
} else {
this.globalData[name] = data
}
isStorage && wx.setStorage({
key: name,
data: this.globalData[name]
})
},
getGlobalDataByKey(name) { // 先从globalData中获取 没有则从缓存取并赋值给globalData
let gVal = this.globalData[name]
if (typeof gVal === 'object' && Object.keys(gVal).length !== 0) {
return gVal
}else if(typeof gVal === 'string' && gVal !== '') return gVal
let value = this.getStorageSync(name)
if (value) {
this.globalData[name] = value
}
return value
},
isLogin: function () {
return this.globalData.userInfo.uid > 0 ? true : false
},
getUid: function () {
let userInfo = this.getGlobalDataByKey('userInfo');
return userInfo && userInfo.uid || 0;
},
setUdid() {
let udid = uuid().replace(/-/g, '')
this.setGlobalData('udid', udid)
},
setSystemInfo() {
try {
const res = wx.getSystemInfoSync()
this.setGlobalData('systemInfo',res)
} catch (e) {
// Do something when catch error
}
},
getNetworkType() {
return new Promise(resolve => {
wx.getNetworkType({
success: function (res) {
let net = '0'
let networkType = res.networkType
if (networkType === 'wifi') {
net = '1';
} else if (networkType === '2g') {
net = '2';
} else if (networkType === '3g') {
net = '3';
} else if (networkType === '4g') {
net = '4';
} else {
net = '0';
}
resolve(net)
}
})
})
}
}