util.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. const api = require('./api.js');
  2. const dont_login_api = require('./config_api.js').dont_login;
  3. const no_openid_api = require('./config_api.js').no_openid;
  4. class Utils {
  5. /**
  6. * @that {OBject} 挂载对象
  7. */
  8. constructor(that) {
  9. this.api = api;
  10. this._showModel = false;
  11. this._loading = false;
  12. // this.message_hint = {
  13. // 100: '继续发送请求'
  14. // };
  15. that.kx_request = this.$request.bind(this);
  16. that.kx_api = this.api;
  17. }
  18. /*
  19. 获取实际数据类型
  20. @data {any} 数据
  21. */
  22. getDataType(data) {
  23. return /^\[object (.*)\]$/.exec(Object.prototype.toString.call(data))[1];
  24. }
  25. /*
  26. 格式化时间
  27. @date {Date} 传入的时间
  28. @status {Boolean} 是否需要时分秒开关 true 关闭时分秒选项 false 打开时分秒选项
  29. */
  30. formatTime(date, status = false) {
  31. date = date.replace(getRegExp('-', 'g'), '/');
  32. const _date = new Date(date);
  33. const year = _date.getFullYear();
  34. const month = _date.getMonth() + 1;
  35. const day = _date.getDate();
  36. const hour = _date.getHours();
  37. const minute = _date.getMinutes();
  38. const second = _date.getSeconds();
  39. if (status) {
  40. return [year, month, day].map(this.formatNumber).join('/');
  41. }
  42. return [year, month, day].map(this.formatNumber).join('/') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
  43. }
  44. /* 格式化数字 */
  45. formatNumber(n) {
  46. n = n.toString();
  47. return n[1] ? n : '0' + n;
  48. }
  49. /*
  50. 获取url
  51. @url {String} 待处理的URL
  52. @return {String} 处理过的字符串
  53. 根据URL是否有http或者https判断是否拼接字符串
  54. */
  55. getUrl(url) {
  56. return new Promise(reslove => {
  57. const apiUrl = require('../config.js').apiUrl; // 加载接口地址文件
  58. if (url.indexOf('https://') === -1 && url.indexOf('http://') === -1) {
  59. reslove(apiUrl + url)
  60. } else {
  61. if (url.indexOf('http://') === -1) {
  62. reslove(url)
  63. return
  64. }
  65. reslove(url.replace('http://', 'https://'))
  66. }
  67. })
  68. }
  69. /*
  70. 获取Openid
  71. @options {Object} request请求的参数
  72. @return 返回获取到的openID加入options并返回
  73. */
  74. getOpenid() {
  75. return new Promise((resolve, reject) => {
  76. const _openid = wx.getStorageSync('openid');
  77. if (_openid) {
  78. resolve(_openid);
  79. } else {
  80. wx.login({
  81. success: (res) => {
  82. const code = res.code;
  83. this.$request({
  84. // url:'',
  85. data: {
  86. code,
  87. },
  88. success: res => {
  89. wx.setStorage({
  90. key: 'openid',
  91. data: res.data.openid,
  92. success: res => {
  93. const openid = res.data.openid
  94. resolve(openid);
  95. }
  96. })
  97. }
  98. })
  99. }
  100. })
  101. }
  102. })
  103. }
  104. /**
  105. * 获取userid与userToken
  106. * @options {Object} 传入的对象参数
  107. * @return 返回参数对象
  108. * 设置request参数中的userID和usertoken
  109. */
  110. getUserId(options) {
  111. return new Promise((reslove, reject) => {
  112. const userid = wx.getStorageSync('userid');
  113. const usertoken = wx.getStorageSync('usertoken');
  114. options.data.user_id = userid;
  115. options.data.user_token = usertoken;
  116. reslove(options)
  117. })
  118. }
  119. /**
  120. * 获取网络状态
  121. */
  122. getNetworkType() {
  123. return new Promise((reslove, reject) => {
  124. wx.getNetworkType({
  125. success: function (res) {
  126. if (res.networkType === 'none') {
  127. wx.$emit('offline', true)
  128. reslove('offline')
  129. } else {
  130. wx.$emit('offline', false)
  131. reslove(res.networkType)
  132. }
  133. },
  134. fail: function (res) {
  135. reject('fail')
  136. }
  137. })
  138. })
  139. }
  140. /*
  141. 请求方法
  142. @options 请求参数
  143. @status 是否携带userID
  144. */
  145. async $request(options) {
  146. /**
  147. * 检测网络状况 并判断是否发起请求
  148. * 当无网络时传入 offline 并提示无网络
  149. */
  150. const networkType = await this.getNetworkType();
  151. if (networkType === 'offline') {
  152. wx.showToast({
  153. icon: 'none',
  154. title: '网络未连接',
  155. })
  156. options.success && options.success(networkType)
  157. return this.getNetworkType()
  158. }
  159. /* 拼接接口地址 */
  160. if (this.getDataType(options.url) !== 'String') {
  161. throw new Error('接口路径格式错误')
  162. }
  163. /*判断是否需要登陆才能调用api */
  164. options.dont_login = false; //默认全部需要登录
  165. if (dont_login_api.length && dont_login_api.includes(options.url)) {
  166. options.dont_login = true;
  167. }
  168. /**判断是否需要openid才能调用api */
  169. options.no_openid = false; //默认全部需要
  170. if (no_openid_api.length && no_openid_api.includes(options.url)) {
  171. options.no_openid = true;
  172. }
  173. /* 设置URL */
  174. options.url = await this.getUrl(options.url);
  175. /* 判断是否传入参数 */
  176. options.data = options.data ? options.data : {};
  177. /* 设置请求方式并转换为大写*/
  178. options.method = (options.type ? options.type : 'get').toUpperCase();
  179. /* 判断是否传入请求头 */
  180. options.header = options.header || {};
  181. /* 判断是否传入返回数据格式 */
  182. options.dataType = options.dataType || 'json';
  183. /* 判断是否传入响应数据格式 */
  184. options.responseType = options.responseType || 'text';
  185. /* 消除空值字段 */
  186. for (let key in options.data) {
  187. if (!options.data[key] && options.data[key] !== 0) {
  188. delete options.data[key]
  189. }
  190. }
  191. /**根据判断写入openid */
  192. // if (!options.no_openid) {
  193. // options.data.openid = await this.getOpenid();
  194. // }
  195. /* 根据dont_login判断是否需要登录 */
  196. if (options.dont_login) {
  197. return this._request(options);
  198. } else {
  199. /* 设置userID和usertoken */
  200. let _options = await this.getUserId(options);
  201. /** 当user_id与user_token不全时 提示登陆重新获取 */
  202. if (_options.data.user_id && _options.data.user_token) {
  203. return this._request(_options);
  204. } else {
  205. this._doLogin();
  206. }
  207. }
  208. }
  209. /**
  210. * 实际执行的请求方法体
  211. * @opt 传入的参数对象
  212. * @return 返回promise对象
  213. * 执行完之后既能执行回调也能返回promise对象调用
  214. */
  215. _request(opt) {
  216. let route = getCurrentPages();
  217. const that = this;
  218. return new Promise((resolve, reject) => {
  219. !this._loading && wx.showLoading({
  220. mask: true,
  221. title: '加载中...',
  222. success: () => {
  223. this._loading = true
  224. }
  225. })
  226. wx.request({
  227. url: opt.url,
  228. data: opt.data,
  229. header: opt.header,
  230. method: opt.method,
  231. dataType: opt.dataType,
  232. responseType: opt.responseType,
  233. success: function (res) {
  234. wx.hideLoading({
  235. success: () => {
  236. this._loading = false;
  237. }
  238. })
  239. // 判断是否含有成功方法并执行
  240. if (opt.success && typeof opt.success === 'function') {
  241. if (res.statusCode === 200) {
  242. const errcode = res.data.errcode;
  243. if (errcode === 0) {
  244. opt.success(res.data);
  245. resolve(res.data);
  246. } else {
  247. // 判断是否含有失败方法并执行
  248. if (opt.fail && typeof opt.fail === 'function') {
  249. opt.fail(res.data);
  250. reject(res.data);
  251. }
  252. if (errcode === 2008) {
  253. that._doLogin(res.data.errmsg + ',请重新登录')
  254. return
  255. }
  256. if (errcode === 2010) {
  257. that._doLogin(res.data.errmsg)
  258. return
  259. }
  260. // model 判断是否自定义模态框或者提示框
  261. if (!opt.model) {
  262. wx.showModal({
  263. title: '提示',
  264. content: res.data.errmsg || '网络异常,请检查后重试',
  265. showCancel: false
  266. })
  267. }
  268. }
  269. } else {
  270. opt.success && opt.success('offline')
  271. wx.showModal({
  272. title: '提示',
  273. content: '网络异常,请检查后重试',
  274. showCancel: false
  275. })
  276. }
  277. }
  278. },
  279. fail: function (res) {
  280. // 判断是否含有失败方法并执行
  281. wx.hideLoading({
  282. success: () => {
  283. this._loading = false;
  284. }
  285. })
  286. if (opt.fail && typeof opt.fail === 'function') {
  287. opt.success && opt.success('offline')
  288. opt.fail(res.data);
  289. reject(res.data);
  290. wx.showModal({
  291. title: '提示',
  292. content: '网络异常,请检查后重试',
  293. showCancel: false
  294. })
  295. }
  296. },
  297. complete: (res) => {
  298. console.log('请求参数=>', opt);
  299. console.log('请求结果=>', res.data.errmsg, res.data);
  300. console.log('服务器响应状态=>', res.statusCode);
  301. console.log('服务器响应结果=>', res);
  302. console.log('当前页面=>', route[route.length - 1].route);
  303. console.log(' ');
  304. wx.stopPullDownRefresh({
  305. success: () => {
  306. console.log(route[route.length - 1].route, '=> stopPullDownRefresh')
  307. }
  308. });
  309. // 判断是否含有complete方法并执行
  310. if (opt.complete && typeof opt.complete === 'function') {
  311. opt.complete(res.data);
  312. resolve(res.data);
  313. }
  314. },
  315. })
  316. })
  317. }
  318. /**
  319. * 执行跳转登录页面操作
  320. */
  321. _doLogin(message = '你还未登录,请立即登录') {
  322. if (!this._showModel) {
  323. this._showModel = true;
  324. wx.showModal({
  325. title: '提示',
  326. content: message,
  327. cancelColor: '#888A8E',
  328. confirmColor: '#31364C',
  329. success: res => {
  330. if (res.confirm) {
  331. wx.navigateTo({
  332. url: '/pages/login/login',
  333. success: () => {
  334. this._showModel = false;
  335. }
  336. })
  337. }
  338. if (res.cancel) {
  339. this._showModel = false;
  340. }
  341. }
  342. })
  343. }
  344. }
  345. /**
  346. * 上传图片
  347. * @pic_arr {Array} 图片数组
  348. * @return {Array}
  349. */
  350. upLoadImage(options) {
  351. const _type = this.getDataType(options.files);
  352. options.formData = options.formData || {};
  353. const formData = {
  354. user_id: wx.getStorageSync('userid'),
  355. user_token: wx.getStorageSync('usertoken'),
  356. ...options.formData
  357. };
  358. !this._loading && wx.showLoading({
  359. mask: true,
  360. title: '上传中...',
  361. success: () => {
  362. this._loading = true
  363. }
  364. })
  365. return new Promise((reslove, reject) => {
  366. if (_type === "Array") {
  367. const _arr = [];
  368. const _files = options.files;
  369. const _len = _files.length - 1;
  370. const _url = this.getUrl(options.url);
  371. _files.forEach((val, key) => {
  372. wx.uploadFile({
  373. url: _url,
  374. filePath: val,
  375. name: options.name,
  376. formData,
  377. success: res => {
  378. if (res.statusCode === 200) {
  379. const data = JSON.parse(res.data);
  380. if (data.errcode === 0) {
  381. _arr.push(data.data);
  382. if (_len === key) {
  383. wx.hideLoading({
  384. success: () => {
  385. this._loading = false;
  386. }
  387. })
  388. reslove(_arr)
  389. }
  390. }
  391. }
  392. },
  393. fail: () => {
  394. reject({
  395. type: this.getDataType(val)
  396. })
  397. throw new Error('输入格式有误')
  398. }
  399. })
  400. })
  401. } else {
  402. reject({
  403. type: _type
  404. })
  405. throw new Error('输入格式有误')
  406. }
  407. })
  408. }
  409. /**
  410. * 获取用户信息
  411. */
  412. getHwUserInfo(that) {
  413. return new Promise(reslove => {
  414. wx.kx_request({
  415. url: wx.kx_api.hwUser.getHwUserInfo,
  416. success: res => {
  417. if (res.data) {
  418. //成功后存入缓存
  419. wx.setStorageSync('userinfo', res.data.hwUser);
  420. reslove(res.data.hwUser)
  421. // 判断是否提交页面数据
  422. that && that.setData({
  423. userinfo: res.data.hwUser
  424. })
  425. }
  426. }
  427. })
  428. })
  429. }
  430. }
  431. module.exports = {
  432. Utils: Utils
  433. }