util.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. const api = require('./api.js')
  2. class Utils {
  3. /**
  4. * @that {OBject} 挂载对象
  5. */
  6. constructor(that) {
  7. this.api = api;
  8. // this.message_hint = {
  9. // 100: '继续发送请求'
  10. // };
  11. that.kx_request = this.request.bind(this);
  12. that.kx_api = this.api;
  13. }
  14. /*
  15. 获取实际数据类型
  16. @data {any} 数据
  17. */
  18. getDataType(data) {
  19. return /^\[object (.*)\]$/.exec(Object.prototype.toString.call(data))[1];
  20. }
  21. /*
  22. 格式化时间
  23. @date {Date} 传入的时间
  24. @status {Boolean} 是否需要时分秒开关 true 关闭时分秒选项 false 打开时分秒选项
  25. */
  26. formatTime(date, status = false) {
  27. const _date = new Date(date);
  28. const year = _date.getFullYear();
  29. const month = _date.getMonth() + 1;
  30. const day = _date.getDate();
  31. const hour = _date.getHours();
  32. const minute = _date.getMinutes();
  33. const second = _date.getSeconds();
  34. if (status) {
  35. return [year, month, day].map(this.formatNumber).join('/');
  36. }
  37. return [year, month, day].map(this.formatNumber).join('/') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
  38. }
  39. /* 格式化数字 */
  40. formatNumber(n) {
  41. n = n.toString();
  42. return n[1] ? n : '0' + n;
  43. }
  44. /*
  45. 获取url
  46. @url {String} 待处理的URL
  47. @return {String} 处理过的字符串
  48. 根据URL是否有http或者https判断是否拼接字符串
  49. */
  50. getUrl(url) {
  51. const apiUrl = require('../config.js').apiUrl; // 加载接口地址文件
  52. if (url.indexOf('https://') === -1 && url.indexOf('http://') === -1) {
  53. return apiUrl + url
  54. } else {
  55. if (url.indexOf('http://') === -1) {
  56. return url
  57. }
  58. return url.replace('http://', 'https://')
  59. }
  60. }
  61. /*
  62. 获取Openid
  63. @options {Object} request请求的参数
  64. @return 返回获取到的openID加入options并返回
  65. */
  66. getOpenid(options) {
  67. return new Promise((resolve, reject) => {
  68. wx.login({
  69. success: (res) => {
  70. let code = res.code;
  71. this.request({
  72. code,
  73. success: res => {
  74. wx.setStorage({
  75. key: 'openid',
  76. data: res.data.openid,
  77. success: res => {
  78. options.openid = res.data.openid
  79. resolve(options);
  80. }
  81. })
  82. }
  83. })
  84. }
  85. })
  86. })
  87. }
  88. /**
  89. * 获取userid与userToken
  90. * @options {Object} 传入的对象参数
  91. * @return 返回参数对象
  92. * 设置request参数中的userID和usertoken
  93. */
  94. getUserId(options) {
  95. const userid = wx.getStorageSync('userid');
  96. const usertoken = wx.getStorageSync('usertoken');
  97. options.data.user_id = userid;
  98. options.data.user_token = usertoken;
  99. return options
  100. }
  101. /*
  102. 请求方法
  103. @options 请求参数
  104. @status 是否携带userID
  105. */
  106. request(options, status = true) {
  107. /* 判断是否传入参数 */
  108. options.data = options.data ? options.data : {};
  109. /* 设置请求方式 */
  110. options.method = (options.type ? options.type : 'get').toUpperCase();
  111. /* 拼接接口地址 */
  112. if (this.getDataType(options.url) !== 'String') {
  113. throw new Error('接口路径格式错误')
  114. }
  115. /* 设置URL */
  116. options.url = this.getUrl(options.url);
  117. /* 消除空值字段 */
  118. // for (let key in options.data) {
  119. // if (options.data[key] === undefined || options.data[key] === '') {
  120. // delete options.data[key]
  121. // }
  122. // }
  123. /**
  124. * 检测网络状况 并判断是否发起请求
  125. * 当无网络时传入 offline 并提示无网络
  126. */
  127. wx.getNetworkType({
  128. success: (res) => {
  129. const networkType = res.networkType
  130. if (networkType === 'none') {
  131. wx.showToast({
  132. icon: 'none',
  133. title: '网络未连接',
  134. })
  135. wx.$emit('offline', true)
  136. options.success && options.success('offline')
  137. return
  138. }
  139. /* 根据需要判断是否传入openID */
  140. if (status) {
  141. /* 获取openID并将入参数 */
  142. // const openid = wx.getStorageSync('openid');
  143. // if (openid) {
  144. // _options.openid = openid;
  145. // this._request(_options);
  146. // } else {
  147. // this.getOpenid(_options).then((data) => {
  148. // this._request(data);
  149. // });
  150. // }
  151. /* 设置userID和usertoken */
  152. let _options = this.getUserId(options);
  153. this._request(_options);
  154. } else {
  155. this._request(options);
  156. }
  157. }
  158. })
  159. }
  160. /**
  161. * 实际执行的请求方法体
  162. * @opt 传入的参数对象
  163. * @return 返回promise对象
  164. * 执行完之后既能执行回调也能返回promise对象调用
  165. */
  166. _request(opt) {
  167. let route = getCurrentPages();
  168. return new Promise((resolve, reject) => {
  169. !wx.kx_loading && wx.showLoading({
  170. mask: true,
  171. success: () => {
  172. wx.kx_loading = true
  173. }
  174. })
  175. wx.request({
  176. url: opt.url,
  177. data: opt.data || {},
  178. header: opt.header || {},
  179. method: opt.method,
  180. dataType: opt.dataType || 'json',
  181. responseType: opt.responseType || 'text',
  182. success: function(res) {
  183. console.log('请求参数=>', opt);
  184. console.log('服务器响应结果=>', res.statusCode, res.data);
  185. // 设置网络状态
  186. wx.$emit('offline', false)
  187. // 判断是否含有成功方法并执行
  188. if (opt.success && typeof opt.success === 'function') {
  189. if (res.statusCode === 200) {
  190. if (res.data.errcode === 0) {
  191. opt.success(res.data);
  192. resolve(res.data);
  193. } else {
  194. // 判断是否含有失败方法并执行
  195. if (opt.fail && typeof opt.fail === 'function') {
  196. opt.fail(res.data);
  197. reject(res.data);
  198. }
  199. // model 判断是否自定义模态框或者提示框
  200. if (!opt.model) {
  201. wx.showModal({
  202. title: '提示',
  203. content: res.data.errmsg || '网络异常,请检查后重试',
  204. showCancel: false
  205. })
  206. }
  207. }
  208. } else {
  209. opt.success && opt.success('offline')
  210. wx.showModal({
  211. title: '提示',
  212. content: '网络异常,请检查后重试',
  213. showCancel: false
  214. })
  215. }
  216. }
  217. },
  218. fail: function(res) {
  219. // 判断是否含有失败方法并执行
  220. if (opt.fail && typeof opt.fail === 'function') {
  221. opt.success && opt.success('offline')
  222. opt.fail(res.data);
  223. reject(res.data);
  224. wx.showModal({
  225. title: '提示',
  226. content: '网络异常,请检查后重试',
  227. showCancel: false
  228. })
  229. }
  230. },
  231. complete: function(res) {
  232. wx.hideLoading({
  233. success: () => {
  234. wx.kx_loading = false;
  235. }
  236. })
  237. console.log('当前页面=>', route[route.length - 1].route);
  238. console.log('请求结果=>', res.data.errmsg || res.data);
  239. // 判断是否含有complete方法并执行
  240. if (opt.complete && typeof opt.complete === 'function') {
  241. opt.complete(res.data);
  242. resolve(res.data);
  243. }
  244. },
  245. })
  246. })
  247. }
  248. /**
  249. * 上传图片
  250. * @pic_arr {Array} 图片数组
  251. * @return {Array}
  252. */
  253. upLoadImage(pic_arr, name) {
  254. let _type = this.getDataType(pic_arr);
  255. return new Promise((reslove, reject) => {
  256. if (_type === "Array") {
  257. let _arr = [];
  258. let _len = pic_arr.length;
  259. pic_arr.forEach((val, key) => {
  260. wx.uploadFile({
  261. url: wx.kx_api.hwUser.changeAvatar,
  262. filePath: val,
  263. name,
  264. formData: {
  265. user_id: wx.getStorageSync('userid'),
  266. user_token: wx.getStorageSync('usertoken'),
  267. },
  268. success: res => {
  269. if (res.statusCode === 200) {
  270. const data = JSON.parse(res.data);
  271. if (data.errcode === 0) {
  272. _arr.push(data.data);
  273. if (_len - 1 === key) {
  274. reslove(_arr)
  275. }
  276. }
  277. }
  278. },
  279. fail: () => {
  280. reject({
  281. type: this.getDataType(val)
  282. })
  283. throw new Error('输入格式有误')
  284. }
  285. })
  286. })
  287. } else {
  288. reject({
  289. type: _type
  290. })
  291. throw new Error('输入格式有误')
  292. }
  293. })
  294. }
  295. /**
  296. * 获取用户信息
  297. */
  298. getHwUserInfo(that) {
  299. wx.kx_request({
  300. url: wx.kx_api.hwUser.getHwUserInfo,
  301. success: res => {
  302. //成功后存入缓存
  303. wx.setStorageSync('userinfo', res.data.hwUser);
  304. that.setData({
  305. userinfo: res.data.hwUser
  306. })
  307. }
  308. })
  309. }
  310. }
  311. module.exports = {
  312. Utils: Utils
  313. }