appInit.js 6.3 KB
Newer Older
1
import uniStarterConfig from '@/uni-starter.config.js';
2
import store from '@/store'
DCloud_JSON's avatar
DCloud_JSON 已提交
3
//应用初始化页
4 5 6
// #ifdef APP-PLUS
import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update';
import callCheckVersion from '@/uni_modules/uni-upgrade-center-app/utils/call-check-version';
DCloud_JSON's avatar
321  
DCloud_JSON 已提交
7
import interceptorChooseImage from '@/uni_modules/json-interceptor-chooseImage/js_sdk/main.js';
8
// #endif
9
const db = uniCloud.database()
10 11 12
export default function() {
	
	setTimeout(()=>{
13
		// uniStarterConfig挂载到getApp().
14
		const app = getApp({allowDefault: true})
15
		app.globalData.config = uniStarterConfig;
16
	},30)
17 18
	
	// 初始化appVersion(仅app生效)
DCloud_JSON's avatar
DCloud_JSON 已提交
19
	initAppVersion();
DCloud_JSON's avatar
321  
DCloud_JSON 已提交
20 21 22 23 24 25
	
	// #ifdef APP-PLUS
	// 实现,路由拦截。当应用无访问摄像头/相册权限,引导跳到设置界面
	interceptorChooseImage()
	// #endif

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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

	//clientDB的错误提示
	function onDBError({
		code, // 错误码详见https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=returnvalue
		message
	}) {
		// 处理错误
		console.log(code,message);
		if([
			'TOKEN_INVALID_INVALID_CLIENTID',
			'TOKEN_INVALID',
			'TOKEN_INVALID_TOKEN_EXPIRED',
			'TOKEN_INVALID_WRONG_TOKEN',
			'TOKEN_INVALID_ANONYMOUS_USER',
		].includes(code)){
			uni.navigateTo({
				url:'/pages/ucenter/login-page/index/index'
			})
		}
	}
	// 绑定clientDB错误事件
	db.on('error', onDBError)
	
	// 解绑clientDB错误事件
	//db.off('error', onDBError)

	db.on('refreshToken', function({
		token,
		tokenExpired
	}) {
		console.log('监听到clientDB的refreshToken',{token,tokenExpired});
		store.commit('user/login', {
			token,
			tokenExpired
		})
	})


	const Debug = true;
	//拦截器封装callFunction
	let callFunctionOption;
	uniCloud.addInterceptor('callFunction',{
		invoke(e){
			console.log(JSON.stringify(e));
			callFunctionOption = e
		},
		complete(e){
			// console.log(JSON.stringify(e));
		},
		fail(e) { // 失败回调拦截
			if(Debug){
				console.log(e);
				uni.showModal({
					content: JSON.stringify(e),
					showCancel: false
				});
			}else{
				uni.showModal({
					content: "系统错误请稍后再试!",
					showCancel: false,
					confirmText:"知道了"
				});
			}
			//如果执行错误,检查是否断网
			uni.getNetworkType({
				complete:res => {
					console.log(res);
					if (res.networkType == 'none') {
						uni.showToast({
							title: '手机网络异常',
							icon: 'none'
						});
						console.log('手机网络异常');
						let callBack = res=>{
							console.log(res);
							if (res.isConnected) {
								uni.showToast({
									title: '恢复联网自动重新执行',
									icon: 'none'
								});
								console.log(res.networkType,"恢复联网自动重新执行");
								uni.offNetworkStatusChange(e=>{
									console.log("移除监听成功",e);
								})
								//恢复联网自动重新执行
								uniCloud.callFunction(callFunctionOption)
								uni.offNetworkStatusChange(callBack);
							}
						}
						uni.onNetworkStatusChange(callBack);
					}
				}
			});
		},
		success:(e)=>{
			console.log(e);
			const {token,tokenExpired} = e.result
			if (token && tokenExpired) {
				store.commit('user/login', {
					token,
					tokenExpired
				})
			}
			
			console.log(e.result.code);
			switch (e.result.code){
				case 403:
					uni.showModal({
						content: '未登陆,跳登陆',
						showCancel: false
					});
					break;
				case 50101:
					uni.showToast({
						title: e.result.msg,
						icon: 'none',
						duration:2000
					});
					break;
				default:
					console.log('code的值是:'+e.result.code,'可以在这里插入,自动处理响应体');
					break;
			}
		}
	})

DCloud_JSON's avatar
DCloud_JSON 已提交
152
	//自定义路由拦截
DCloud_JSON's avatar
DCloud_JSON 已提交
153
	const {"router": {needLogin,login} } = uniStarterConfig //需要登录的页面
154
	let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
DCloud_JSON's avatar
DCloud_JSON 已提交
155
	list.forEach(item => { //用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
156 157
		uni.addInterceptor(item, {
			invoke(e) { // 调用前拦截
DCloud_JSON's avatar
DCloud_JSON 已提交
158
				//获取用户的token
159
				const token = uni.getStorageSync('uni_id_token')
DCloud_JSON's avatar
DCloud_JSON 已提交
160
				//获取当前页面路径(即url去掉"?"和"?"后的参数)
161
				const url = e.url.split('?')[0]
DCloud_JSON's avatar
DCloud_JSON 已提交
162
				//控制登录优先级
163 164 165 166 167 168
				let pages = getCurrentPages();
				if (
					url == '/pages/ucenter/login-page/index/index'
					&&
					pages[pages.length - 1].route.split('/')[2]!='login-page'
				) {
DCloud_JSON's avatar
DCloud_JSON 已提交
169
					//一键登录(univerify)、账号(username)、验证码登录(短信smsCode)
170
					if (login[0] == 'univerify') {
DCloud_JSON's avatar
DCloud_JSON 已提交
171
						if(e.url == url) { e.url += '?' } //添加参数之前判断是否带了`?`号如果没有就补上,因为当开发场景本身有参数的情况下是已经带了`?`号
172 173 174 175
						e.url += "univerify_first=true"
					} else if (login[0] == 'username') {
						e.url = "/pages/ucenter/login-page/pwd-login/pwd-login"
					}
DCloud_JSON's avatar
DCloud_JSON 已提交
176
				}else{
DCloud_JSON's avatar
DCloud_JSON 已提交
177
					//拦截强制登录页面
DCloud_JSON's avatar
DCloud_JSON 已提交
178 179
					if (needLogin.includes(url) && token == '') {
						uni.showToast({
DCloud_JSON's avatar
DCloud_JSON 已提交
180
							title: '请先登录',
DCloud_JSON's avatar
DCloud_JSON 已提交
181 182 183 184 185 186
							icon: 'none'
						})
						return uni.navigateTo({
							url: "/pages/ucenter/login-page/index/index"
						})
					}
187 188 189 190 191 192 193 194
				}
			},
			fail(err) { // 失败回调拦截 
				console.log(err);
			},
		})
	})
// #ifdef APP-PLUS
DCloud_JSON's avatar
DCloud_JSON 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
// 监听并提示设备网络状态变化
	uni.onNetworkStatusChange(res=> {
	    console.log(res.isConnected);
	    console.log(res.networkType);
		if(res.networkType!='none'){
			uni.showToast({
				title:'当前网络类型:'+res.networkType,
				icon:'none',
				duration:3000
			})
		}else{
			uni.showToast({
				title:'网络类型:'+res.networkType,
				icon:'none',
				duration:3000
			})
		}
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	});
// #endif

}
/**
 * // 初始化appVersion
 */
function initAppVersion() {
	// #ifdef APP-PLUS
	let appid = plus.runtime.appid;
	plus.runtime.getProperty(appid, (wgtInfo) => {
		let appVersion = plus.runtime;
		let currentVersion = appVersion.versionCode > wgtInfo.versionCode ? appVersion : wgtInfo;
		getApp({
			allowDefault: true
		}).appVersion = {
			...currentVersion,
			appid,
			hasNew: false
		}
		// 检查更新小红点
		callCheckVersion().then(res => {
DCloud_JSON's avatar
DCloud_JSON 已提交
234
			// console.log('检查是否有可以更新的版本', res);
235 236 237 238 239 240 241 242 243 244 245
			if (res.result.code > 0) {
				// 有新版本
				getApp({
					allowDefault: true
				}).appVersion.hasNew = true;
			}
		})
	});
	// 检查更新
	checkUpdate();
	// #endif
DCloud_JSON's avatar
DCloud_JSON 已提交
246
}