util.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. reslove('offline')
  124. } else {
  125. reslove(res.networkType)
  126. }
  127. },
  128. fail: function(res) {
  129. reject('fail')
  130. }
  131. })
  132. })
  133. }
  134. /*
  135. 请求方法
  136. @options 请求参数
  137. @status 是否携带userID
  138. */
  139. async request(options) {
  140. /* 拼接接口地址 */
  141. if (this.getDataType(options.url) !== 'String') {
  142. throw new Error('接口路径格式错误')
  143. }
  144. /*判断是否需要登陆才能调用api */
  145. options.dont_login = false; //默认全部需要登录
  146. if (dont_login_api.length && dont_login_api.includes(options.url)) {
  147. options.dont_login = true;
  148. }
  149. /**判断是否需要openid才能调用api */
  150. options.no_openid = false; //默认全部需要
  151. if (no_openid_api.length && no_openid_api.includes(options.url)) {
  152. options.no_openid = true;
  153. }
  154. /* 设置URL */
  155. options.url = this.getUrl(options.url);
  156. /* 判断是否传入参数 */
  157. options.data = options.data ? options.data : {};
  158. /* 设置请求方式并转换为大写*/
  159. options.method = (options.type ? options.type : 'get').toUpperCase();
  160. /* 判断是否传入请求头 */
  161. options.header = options.header || {};
  162. /* 判断是否传入返回数据格式 */
  163. options.dataType = options.dataType || 'json';
  164. /* 判断是否传入响应数据格式 */
  165. options.responseType = options.responseType || 'text';
  166. /* 消除空值字段 */
  167. // for (let key in options.data) {
  168. // if (!options.data[key] && options.data[key] !== 0) {
  169. // delete options.data[key]
  170. // }
  171. // }
  172. /**
  173. * 检测网络状况 并判断是否发起请求
  174. * 当无网络时传入 offline 并提示无网络
  175. */
  176. const networkType = await this.getNetworkType();
  177. if (networkType === 'offline') {
  178. wx.showToast({
  179. icon: 'none',
  180. title: '网络未连接',
  181. })
  182. wx.$emit('offline', true)
  183. options.success && options.success(networkType)
  184. return this.getNetworkType()
  185. } else {
  186. /**根据判断写入openid */
  187. // if (!options.no_openid) {
  188. // options.data.openid = await this.getOpenid();
  189. // }
  190. /* 根据dont_login判断是否需要登录 */
  191. if (options.dont_login) {
  192. return this._request(options);
  193. } else {
  194. /* 设置userID和usertoken */
  195. let _options = await this.getUserId(options);
  196. /** 当user_id与user_token不全时 提示登陆重新获取 */
  197. if (_options.data.user_id && _options.data.user_token) {
  198. return this._request(_options);
  199. } else {
  200. this._doLogin();
  201. }
  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. wx.$emit('offline', false)
  231. // 判断是否含有成功方法并执行
  232. if (opt.success && typeof opt.success === 'function') {
  233. if (res.statusCode === 200) {
  234. if (res.data.errcode === 0) {
  235. opt.success(res.data);
  236. resolve(res.data);
  237. } else {
  238. // 判断是否含有失败方法并执行
  239. if (opt.fail && typeof opt.fail === 'function') {
  240. opt.fail(res.data);
  241. reject(res.data);
  242. }
  243. // model 判断是否自定义模态框或者提示框
  244. if (!opt.model) {
  245. wx.showModal({
  246. title: '提示',
  247. content: res.data.errmsg || '网络异常,请检查后重试',
  248. showCancel: false
  249. })
  250. }
  251. }
  252. } else {
  253. opt.success && opt.success('offline')
  254. wx.showModal({
  255. title: '提示',
  256. content: '网络异常,请检查后重试',
  257. showCancel: false
  258. })
  259. }
  260. }
  261. },
  262. fail: function(res) {
  263. // 判断是否含有失败方法并执行
  264. if (opt.fail && typeof opt.fail === 'function') {
  265. opt.success && opt.success('offline')
  266. opt.fail(res.data);
  267. reject(res.data);
  268. wx.showModal({
  269. title: '提示',
  270. content: '网络异常,请检查后重试',
  271. showCancel: false
  272. })
  273. }
  274. },
  275. complete: (res) => {
  276. console.log('请求参数=>', opt);
  277. console.log('请求结果=>', res.data.errmsg, res.data);
  278. console.log('服务器响应状态=>', res.statusCode);
  279. console.log('服务器响应结果=>', res);
  280. console.log('当前页面=>', route[route.length - 1].route);
  281. console.log(' ');
  282. wx.hideLoading({
  283. success: () => {
  284. this._loading = false;
  285. }
  286. })
  287. wx.stopPullDownRefresh({
  288. success: () => {
  289. console.log(route[route.length - 1].route, '=> stopPullDownRefresh')
  290. }
  291. });
  292. // 判断是否含有complete方法并执行
  293. if (opt.complete && typeof opt.complete === 'function') {
  294. opt.complete(res.data);
  295. resolve(res.data);
  296. }
  297. },
  298. })
  299. })
  300. }
  301. /**
  302. * 执行跳转登录页面操作
  303. */
  304. _doLogin() {
  305. // wx.clearStorageSync();
  306. if (!this._showModel) {
  307. this._showModel = true;
  308. wx.reLaunch({
  309. url: '/pages/login/login',
  310. success: () => {
  311. setTimeout(() => {
  312. wx.showModal({
  313. title: '提示',
  314. content: '登陆状态失效,请重新登录',
  315. showCancel: false,
  316. success: () => {
  317. this._showModel = false;
  318. }
  319. })
  320. }, 300)
  321. }
  322. })
  323. }
  324. }
  325. /**
  326. * 上传图片
  327. * @pic_arr {Array} 图片数组
  328. * @return {Array}
  329. */
  330. upLoadImage(options) {
  331. const _type = this.getDataType(options.files);
  332. options.formData = options.formData || {};
  333. const formData = {
  334. user_id: wx.getStorageSync('userid'),
  335. user_token: wx.getStorageSync('usertoken'),
  336. ...options.formData
  337. }
  338. return new Promise((reslove, reject) => {
  339. if (_type === "Array") {
  340. const _arr = [];
  341. const _files = options.files;
  342. const _len = _files.length - 1;
  343. const _url = this.getUrl(options.url);
  344. _files.forEach((val, key) => {
  345. wx.uploadFile({
  346. url: _url,
  347. filePath: val,
  348. name: options.name,
  349. formData,
  350. success: res => {
  351. if (res.statusCode === 200) {
  352. const data = JSON.parse(res.data);
  353. if (data.errcode === 0) {
  354. _arr.push(data.data);
  355. if (_len === key) {
  356. reslove(_arr)
  357. }
  358. }
  359. }
  360. },
  361. fail: () => {
  362. reject({
  363. type: this.getDataType(val)
  364. })
  365. throw new Error('输入格式有误')
  366. }
  367. })
  368. })
  369. } else {
  370. reject({
  371. type: _type
  372. })
  373. throw new Error('输入格式有误')
  374. }
  375. })
  376. }
  377. /**
  378. * 获取用户信息
  379. */
  380. getHwUserInfo(that) {
  381. wx.kx_request({
  382. url: wx.kx_api.hwUser.getHwUserInfo,
  383. success: res => {
  384. //成功后存入缓存
  385. wx.setStorageSync('userinfo', res.data.hwUser);
  386. that.setData({
  387. userinfo: res.data.hwUser
  388. })
  389. }
  390. })
  391. }
  392. }
  393. module.exports = {
  394. Utils: Utils
  395. }