util.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /*
  2. * @Author: your name
  3. * @Date: 2021-06-23 22:15:11
  4. * @LastEditTime: 2021-06-25 00:23:00
  5. * @LastEditors: Please set LastEditors
  6. * @Description: In User Settings Edit
  7. * @FilePath: \Mina_B_T\miniprogram\utils\util.ts
  8. */
  9. import { getHwUserInfoApi } from "../service/hwUser";
  10. import { apiUrl } from "../config"; // 加载接口地址文件
  11. /**
  12. * 执行跳转登录页面操作
  13. */
  14. export function login(message: string = '你还未登录,请立即登录') {
  15. wx.showModal({
  16. title: '提示',
  17. content: message,
  18. cancelColor: '#888A8E',
  19. confirmColor: '#31364C',
  20. success: res => {
  21. if (res.confirm) {
  22. wx.reLaunch({
  23. url: '/pages/login/login',
  24. })
  25. }
  26. }
  27. })
  28. }
  29. /*
  30. 格式化时间
  31. @date {Date} 传入的时间
  32. @status {Boolean} 是否需要时分秒开关 true 关闭时分秒选项 false 打开时分秒选项
  33. */
  34. export function formatTime(date: string, status: boolean = false) {
  35. date = date.replace(RegExp('-', 'g'), '/');
  36. const _date = new Date(date);
  37. const year = _date.getFullYear();
  38. const month = _date.getMonth() + 1;
  39. const day = _date.getDate();
  40. const hour = _date.getHours();
  41. const minute = _date.getMinutes();
  42. const second = _date.getSeconds();
  43. if (status) {
  44. return [year, month, day].map(formatNumber).join('/');
  45. }
  46. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
  47. }
  48. /* 格式化数字 */
  49. export function formatNumber(n: number | string): string {
  50. n = n.toString();
  51. return n[1] ? n : '0' + n;
  52. }
  53. /*
  54. 获取实际数据类型
  55. @data {any} 数据
  56. */
  57. export function getDataType(data: any) {
  58. const result = /^\[object (.*)\]$/.exec(Object.prototype.toString.call(data));
  59. if (result) {
  60. return result[1]
  61. }
  62. return ''
  63. }
  64. /*
  65. 获取url
  66. @url {String} 待处理的URL
  67. @return {String} 处理过的字符串
  68. 根据URL是否有http或者https判断是否拼接字符串
  69. */
  70. export function getUrl(url: string): Promise<string> {
  71. return new Promise(resolve => {
  72. if (url.indexOf('https://') === -1 && url.indexOf('http://') === -1) {
  73. resolve(apiUrl + url)
  74. } else {
  75. if (url.indexOf('http://') === -1) {
  76. resolve(url)
  77. return
  78. }
  79. resolve(url.replace('http://', 'https://'))
  80. }
  81. })
  82. }
  83. /**
  84. * 获取网络状态
  85. */
  86. export function getNetworkType(): Promise<string> {
  87. return new Promise((resolve, reject) => {
  88. wx.getNetworkType({
  89. success: function (res) {
  90. if (res.networkType === 'none') {
  91. resolve('offline')
  92. } else {
  93. resolve(res.networkType)
  94. }
  95. },
  96. fail: function () {
  97. reject('fail')
  98. }
  99. })
  100. })
  101. }
  102. /**
  103. * 获取userid与userToken
  104. * @options {Object} 传入的对象参数
  105. * @return 返回参数对象
  106. * 设置request参数中的userID和usertoken
  107. */
  108. export function getUserId(data: any) {
  109. return new Promise((reslove) => {
  110. const userId = wx.getStorageSync('userId');
  111. const userToken = wx.getStorageSync('userToken');
  112. data.user_id = userId;
  113. data.user_token = userToken;
  114. reslove(data)
  115. })
  116. }
  117. export function isValidKey(key: string | number | symbol, object: object): key is keyof typeof object {
  118. return key in object;
  119. }
  120. /**
  121. * 上传图片
  122. * @pic_arr {Array} 图片数组
  123. * @return {Array}
  124. */
  125. export function upLoadImage(options: { files: string[]; formData?: {}; url: string; name: string; }): Promise<any> {
  126. const _type = getDataType(options.files);
  127. options.formData = options.formData || {};
  128. const formData = {
  129. user_id: wx.getStorageSync('userId'),
  130. user_token: wx.getStorageSync('userToken'),
  131. ...options.formData
  132. };
  133. wx.showLoading({
  134. mask: true,
  135. title: '上传中...'
  136. })
  137. return new Promise(async (resolve, reject) => {
  138. if (_type === "Array") {
  139. const _arr: string[] = [];
  140. const _files = options.files;
  141. const _len = _files.length - 1;
  142. const _url: string = await getUrl(options.url);
  143. _files.forEach((val: string, key: number) => {
  144. wx.uploadFile({
  145. url: _url,
  146. filePath: val,
  147. name: options.name,
  148. formData,
  149. success: res => {
  150. if (res.statusCode === 200) {
  151. const data = JSON.parse(res.data);
  152. if (data.errcode === 0) {
  153. _arr.push(data.data);
  154. if (_len === key) {
  155. wx.hideLoading()
  156. resolve(_arr)
  157. }
  158. }
  159. }
  160. },
  161. fail: (e: any) => {
  162. console.log(e)
  163. reject({
  164. type: getDataType(val)
  165. })
  166. wx.hideLoading()
  167. throw new Error(e)
  168. }
  169. })
  170. })
  171. } else {
  172. reject({
  173. type: _type
  174. })
  175. wx.hideLoading()
  176. throw new Error('输入格式有误')
  177. }
  178. })
  179. }
  180. /**
  181. * 获取用户信息
  182. */
  183. export function getHwUserInfo() {
  184. return new Promise(resolve => {
  185. getHwUserInfoApi().then(data => {
  186. const res = <responseOptionsType>data
  187. if (res.data) {
  188. //成功后存入缓存
  189. wx.setStorageSync('userInfo', res.data.hwUser);
  190. resolve(res.data.hwUser)
  191. }
  192. }).catch(error => {
  193. console.error(error);
  194. })
  195. })
  196. }
  197. /**
  198. * 设置可过期的缓存
  199. * @param key
  200. * @param value
  201. * @param time
  202. */
  203. export function putStorageSync(key: string, value: any, time: number): void {
  204. wx.setStorageSync(key, value)
  205. const _time: number = Date.now()
  206. wx.setStorageSync(key + 'redis', _time + time)
  207. }
  208. /**
  209. * 获取可过期缓存
  210. * @param key
  211. */
  212. export function getStorageSync(key: string): any {
  213. const time: number = wx.getStorageSync(key + 'redis')
  214. if (Date.now() > time) {
  215. wx.removeStorageSync(key)
  216. wx.removeStorageSync(key + 'redis')
  217. return ''
  218. } else {
  219. return wx.getStorageSync(key)
  220. }
  221. }