util.js 12 KB

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