| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326 |
- const api = require('./api.js')
- class Utils {
- /**
- * @that {OBject} 挂载对象
- */
- constructor(that) {
- this.api = api;
- // 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) {
- 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) {
- const apiUrl = require('../config.js').apiUrl; // 加载接口地址文件
- if (url.indexOf('https://') === -1 && url.indexOf('http://') === -1) {
- return apiUrl + url
- } else {
- if (url.indexOf('http://') === -1) {
- return url
- }
- return url.replace('http://', 'https://')
- }
- }
- /*
- 获取Openid
- @options {Object} request请求的参数
- @return 返回获取到的openID加入options并返回
- */
- getOpenid(options) {
- return new Promise((resolve, reject) => {
- wx.login({
- success: (res) => {
- let code = res.code;
- this.request({
- code,
- success: res => {
- wx.setStorage({
- key: 'openid',
- data: res.data.openid,
- success: res => {
- options.openid = res.data.openid
- resolve(options);
- }
- })
- }
- })
- }
- })
- })
- }
- /**
- * 获取userid与userToken
- * @options {Object} 传入的对象参数
- * @return 返回参数对象
- * 设置request参数中的userID和usertoken
- */
- getUserId(options) {
- const userid = wx.getStorageSync('userid');
- const usertoken = wx.getStorageSync('usertoken');
- options.data.user_id = userid;
- options.data.user_token = usertoken;
- return options
- }
- /*
- 请求方法
- @options 请求参数
- @status 是否携带userID
- */
- request(options, status = true) {
- /* 判断是否传入参数 */
- options.data = options.data ? options.data : {};
- /* 设置请求方式 */
- options.method = (options.type ? options.type : 'get').toUpperCase();
- /* 拼接接口地址 */
- if (this.getDataType(options.url) !== 'String') {
- throw new Error('接口路径格式错误')
- }
- /* 设置URL */
- options.url = this.getUrl(options.url);
- /* 消除空值字段 */
- // for (let key in options.data) {
- // if (options.data[key] === undefined || options.data[key] === '') {
- // delete options.data[key]
- // }
- // }
- /**
- * 检测网络状况 并判断是否发起请求
- * 当无网络时传入 offline 并提示无网络
- */
- wx.getNetworkType({
- success: (res) => {
- const networkType = res.networkType
- if (networkType === 'none') {
- wx.showToast({
- icon: 'none',
- title: '网络未连接',
- })
- wx.$emit('offline', true)
- options.success && options.success('offline')
- return
- }
- /* 根据需要判断是否传入openID */
- if (status) {
- /* 获取openID并将入参数 */
- // const openid = wx.getStorageSync('openid');
- // if (openid) {
- // _options.openid = openid;
- // this._request(_options);
- // } else {
- // this.getOpenid(_options).then((data) => {
- // this._request(data);
- // });
- // }
- /* 设置userID和usertoken */
- let _options = this.getUserId(options);
- this._request(_options);
- } else {
- this._request(options);
- }
- }
- })
- }
- /**
- * 实际执行的请求方法体
- * @opt 传入的参数对象
- * @return 返回promise对象
- * 执行完之后既能执行回调也能返回promise对象调用
- */
- _request(opt) {
- let route = getCurrentPages();
- return new Promise((resolve, reject) => {
- !wx.kx_loading && wx.showLoading({
- mask: true,
- success: () => {
- wx.kx_loading = true
- }
- })
- wx.request({
- url: opt.url,
- data: opt.data || {},
- header: opt.header || {},
- method: opt.method,
- dataType: opt.dataType || 'json',
- responseType: opt.responseType || 'text',
- success: function(res) {
- console.log('请求参数=>', opt);
- console.log('服务器响应结果=>', res.statusCode, res.data);
- // 设置网络状态
- wx.$emit('offline', false)
- // 判断是否含有成功方法并执行
- if (opt.success && typeof opt.success === 'function') {
- if (res.statusCode === 200) {
- if (res.data.errcode === 0) {
- opt.success(res.data);
- resolve(res.data);
- } else {
- // 判断是否含有失败方法并执行
- if (opt.fail && typeof opt.fail === 'function') {
- opt.fail(res.data);
- reject(res.data);
- }
- // 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) {
- // 判断是否含有失败方法并执行
- 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: function(res) {
- wx.hideLoading({
- success: () => {
- wx.kx_loading = false;
- }
- })
- console.log('当前页面=>', route[route.length - 1].route);
- console.log('请求结果=>', res.data.errmsg || res.data);
- // 判断是否含有complete方法并执行
- if (opt.complete && typeof opt.complete === 'function') {
- opt.complete(res.data);
- resolve(res.data);
- }
- },
- })
- })
- }
- /**
- * 上传图片
- * @pic_arr {Array} 图片数组
- * @return {Array}
- */
- upLoadImage(pic_arr, name) {
- let _type = this.getDataType(pic_arr);
- return new Promise((reslove, reject) => {
- if (_type === "Array") {
- let _arr = [];
- let _len = pic_arr.length;
- pic_arr.forEach((val, key) => {
- wx.uploadFile({
- url: wx.kx_api.hwUser.changeAvatar,
- filePath: val,
- name,
- formData: {
- user_id: wx.getStorageSync('userid'),
- user_token: wx.getStorageSync('usertoken'),
- },
- success: res => {
- if (res.statusCode === 200) {
- const data = JSON.parse(res.data);
- if (data.errcode === 0) {
- _arr.push(data.data);
- if (_len - 1 === key) {
- reslove(_arr)
- }
- }
- }
- },
- fail: () => {
- reject({
- type: this.getDataType(val)
- })
- throw new Error('输入格式有误')
- }
- })
- })
- } else {
- reject({
- type: _type
- })
- throw new Error('输入格式有误')
- }
- })
- }
- /**
- * 获取用户信息
- */
- getHwUserInfo(that) {
- wx.kx_request({
- url: wx.kx_api.hwUser.getHwUserInfo,
- success: res => {
- //成功后存入缓存
- wx.setStorageSync('userinfo', res.data.hwUser);
- that.setData({
- userinfo: res.data.hwUser
- })
- }
- })
- }
- }
- module.exports = {
- Utils: Utils
- }
|