| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455 |
- const api = require('./api.js');
- const dont_login_api = require('./config_api.js').dont_login;
- const no_openid_api = require('./config_api.js').no_openid;
- class Utils {
- /**
- * @that {OBject} 挂载对象
- */
- constructor(that) {
- this.api = api;
- this._showModel = false;
- this._loading = false;
- // this.message_hint = {
- // 100: '继续发送请求'
- // };
- that.kx_request = this.$request.bind(this);
- that.kx_api = this.api;
- }
- /*
- 获取实际数据类型
- @data {any} 数据
- */
- getDataType(data) {
- return /^\[object (.*)\]$/.exec(Object.prototype.toString.call(data))[1];
- }
- /*
- 格式化时间
- @date {Date} 传入的时间
- @status {Boolean} 是否需要时分秒开关 true 关闭时分秒选项 false 打开时分秒选项
- */
- formatTime(date, status = false) {
- date = date.replace(getRegExp('-', 'g'), '/');
- const _date = new Date(date);
- const year = _date.getFullYear();
- const month = _date.getMonth() + 1;
- const day = _date.getDate();
- const hour = _date.getHours();
- const minute = _date.getMinutes();
- const second = _date.getSeconds();
- if (status) {
- return [year, month, day].map(this.formatNumber).join('/');
- }
- return [year, month, day].map(this.formatNumber).join('/') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
- }
- /* 格式化数字 */
- formatNumber(n) {
- n = n.toString();
- return n[1] ? n : '0' + n;
- }
- /*
- 获取url
- @url {String} 待处理的URL
- @return {String} 处理过的字符串
- 根据URL是否有http或者https判断是否拼接字符串
- */
- getUrl(url) {
- return new Promise(reslove => {
- const apiUrl = require('../config.js').apiUrl; // 加载接口地址文件
- if (url.indexOf('https://') === -1 && url.indexOf('http://') === -1) {
- reslove(apiUrl + url)
- } else {
- if (url.indexOf('http://') === -1) {
- reslove(url)
- return
- }
- reslove(url.replace('http://', 'https://'))
- }
- })
- }
- /*
- 获取Openid
- @options {Object} request请求的参数
- @return 返回获取到的openID加入options并返回
- */
- getOpenid() {
- return new Promise((resolve, reject) => {
- const _openid = wx.getStorageSync('openid');
- if (_openid) {
- resolve(_openid);
- } else {
- wx.login({
- success: (res) => {
- const code = res.code;
- this.$request({
- // url:'',
- data: {
- code,
- },
- success: res => {
- wx.setStorage({
- key: 'openid',
- data: res.data.openid,
- success: res => {
- const openid = res.data.openid
- resolve(openid);
- }
- })
- }
- })
- }
- })
- }
- })
- }
- /**
- * 获取userid与userToken
- * @options {Object} 传入的对象参数
- * @return 返回参数对象
- * 设置request参数中的userID和usertoken
- */
- getUserId(options) {
- return new Promise((reslove, reject) => {
- const userid = wx.getStorageSync('userid');
- const usertoken = wx.getStorageSync('usertoken');
- options.data.user_id = userid;
- options.data.user_token = usertoken;
- reslove(options)
- })
- }
- /**
- * 获取网络状态
- */
- getNetworkType() {
- return new Promise((reslove, reject) => {
- wx.getNetworkType({
- success: function (res) {
- if (res.networkType === 'none') {
- wx.$emit('offline', true)
- reslove('offline')
- } else {
- wx.$emit('offline', false)
- reslove(res.networkType)
- }
- },
- fail: function (res) {
- reject('fail')
- }
- })
- })
- }
- /*
- 请求方法
- @options 请求参数
- @status 是否携带userID
- */
- async $request(options) {
- /**
- * 检测网络状况 并判断是否发起请求
- * 当无网络时传入 offline 并提示无网络
- */
- const networkType = await this.getNetworkType();
- if (networkType === 'offline') {
- wx.showToast({
- icon: 'none',
- title: '网络未连接',
- })
- options.success && options.success(networkType)
- return this.getNetworkType()
- }
- /* 拼接接口地址 */
- if (this.getDataType(options.url) !== 'String') {
- throw new Error('接口路径格式错误')
- }
- /*判断是否需要登陆才能调用api */
- options.dont_login = false; //默认全部需要登录
- if (dont_login_api.length && dont_login_api.includes(options.url)) {
- options.dont_login = true;
- }
- /**判断是否需要openid才能调用api */
- options.no_openid = false; //默认全部需要
- if (no_openid_api.length && no_openid_api.includes(options.url)) {
- options.no_openid = true;
- }
- /* 设置URL */
- options.url = await this.getUrl(options.url);
- /* 判断是否传入参数 */
- options.data = options.data ? options.data : {};
- /* 设置请求方式并转换为大写*/
- options.method = (options.type ? options.type : 'get').toUpperCase();
- /* 判断是否传入请求头 */
- options.header = options.header || {};
- /* 判断是否传入返回数据格式 */
- options.dataType = options.dataType || 'json';
- /* 判断是否传入响应数据格式 */
- options.responseType = options.responseType || 'text';
- /* 消除空值字段 */
- for (let key in options.data) {
- if (!options.data[key] && options.data[key] !== 0) {
- delete options.data[key]
- }
- }
- /**根据判断写入openid */
- // if (!options.no_openid) {
- // options.data.openid = await this.getOpenid();
- // }
- /* 根据dont_login判断是否需要登录 */
- if (options.dont_login) {
- return this._request(options);
- } else {
- /* 设置userID和usertoken */
- let _options = await this.getUserId(options);
- /** 当user_id与user_token不全时 提示登陆重新获取 */
- if (_options.data.user_id && _options.data.user_token) {
- return this._request(_options);
- } else {
- this._doLogin();
- }
- }
- }
- /**
- * 实际执行的请求方法体
- * @opt 传入的参数对象
- * @return 返回promise对象
- * 执行完之后既能执行回调也能返回promise对象调用
- */
- _request(opt) {
- let route = getCurrentPages();
- const that = this;
- return new Promise((resolve, reject) => {
- !this._loading && wx.showLoading({
- mask: true,
- title: '加载中...',
- success: () => {
- this._loading = true
- }
- })
- wx.request({
- url: opt.url,
- data: opt.data,
- header: opt.header,
- method: opt.method,
- dataType: opt.dataType,
- responseType: opt.responseType,
- success: function (res) {
- wx.hideLoading({
- success: () => {
- this._loading = false;
- }
- })
- // 判断是否含有成功方法并执行
- if (opt.success && typeof opt.success === 'function') {
- if (res.statusCode === 200) {
- const errcode = res.data.errcode;
- if (errcode === 0) {
- opt.success(res.data);
- resolve(res.data);
- } else {
- // 判断是否含有失败方法并执行
- if (opt.fail && typeof opt.fail === 'function') {
- opt.fail(res.data);
- reject(res.data);
- }
- if (errcode === 2008) {
- that._doLogin(res.data.errmsg + ',请重新登录')
- return
- }
- if (errcode === 2010) {
- that._doLogin(res.data.errmsg)
- return
- }
- // model 判断是否自定义模态框或者提示框
- if (!opt.model) {
- wx.showModal({
- title: '提示',
- content: res.data.errmsg || '网络异常,请检查后重试',
- showCancel: false
- })
- }
- }
- } else {
- opt.success && opt.success('offline')
- wx.showModal({
- title: '提示',
- content: '网络异常,请检查后重试',
- showCancel: false
- })
- }
- }
- },
- fail: function (res) {
- // 判断是否含有失败方法并执行
- wx.hideLoading({
- success: () => {
- this._loading = false;
- }
- })
- if (opt.fail && typeof opt.fail === 'function') {
- opt.success && opt.success('offline')
- opt.fail(res.data);
- reject(res.data);
- wx.showModal({
- title: '提示',
- content: '网络异常,请检查后重试',
- showCancel: false
- })
- }
- },
- complete: (res) => {
- console.log('请求参数=>', opt);
- console.log('请求结果=>', res.data.errmsg, res.data);
- console.log('服务器响应状态=>', res.statusCode);
- console.log('服务器响应结果=>', res);
- console.log('当前页面=>', route[route.length - 1].route);
- console.log(' ');
- wx.stopPullDownRefresh({
- success: () => {
- console.log(route[route.length - 1].route, '=> stopPullDownRefresh')
- }
- });
- // 判断是否含有complete方法并执行
- if (opt.complete && typeof opt.complete === 'function') {
- opt.complete(res.data);
- resolve(res.data);
- }
- },
- })
- })
- }
- /**
- * 执行跳转登录页面操作
- */
- _doLogin(message = '你还未登录,请立即登录') {
- if (!this._showModel) {
- this._showModel = true;
- wx.showModal({
- title: '提示',
- content: message,
- cancelColor: '#888A8E',
- confirmColor: '#31364C',
- success: res => {
- if (res.confirm) {
- wx.navigateTo({
- url: '/pages/login/login',
- success: () => {
- this._showModel = false;
- }
- })
- }
- if (res.cancel) {
- this._showModel = false;
- }
- }
- })
- }
- }
- /**
- * 上传图片
- * @pic_arr {Array} 图片数组
- * @return {Array}
- */
- upLoadImage(options) {
- const _type = this.getDataType(options.files);
- options.formData = options.formData || {};
- const formData = {
- user_id: wx.getStorageSync('userid'),
- user_token: wx.getStorageSync('usertoken'),
- ...options.formData
- };
- !this._loading && wx.showLoading({
- mask: true,
- title: '上传中...',
- success: () => {
- this._loading = true
- }
- })
- return new Promise((reslove, reject) => {
- if (_type === "Array") {
- const _arr = [];
- const _files = options.files;
- const _len = _files.length - 1;
- const _url = this.getUrl(options.url);
- _files.forEach((val, key) => {
- wx.uploadFile({
- url: _url,
- filePath: val,
- name: options.name,
- formData,
- success: res => {
- if (res.statusCode === 200) {
- const data = JSON.parse(res.data);
- if (data.errcode === 0) {
- _arr.push(data.data);
- if (_len === key) {
- wx.hideLoading({
- success: () => {
- this._loading = false;
- }
- })
- reslove(_arr)
- }
- }
- }
- },
- fail: () => {
- reject({
- type: this.getDataType(val)
- })
- throw new Error('输入格式有误')
- }
- })
- })
- } else {
- reject({
- type: _type
- })
- throw new Error('输入格式有误')
- }
- })
- }
- /**
- * 获取用户信息
- */
- getHwUserInfo(that) {
- return new Promise(reslove => {
- wx.kx_request({
- url: wx.kx_api.hwUser.getHwUserInfo,
- success: res => {
- if (res.data) {
- //成功后存入缓存
- wx.setStorageSync('userinfo', res.data.hwUser);
- reslove(res.data.hwUser)
- // 判断是否提交页面数据
- that && that.setData({
- userinfo: res.data.hwUser
- })
- }
- }
- })
- })
- }
- }
- module.exports = {
- Utils: Utils
- }
|