util.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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.userId = userId;
  114. data.userid = userId;
  115. data.userToken = userToken;
  116. data.user_token = userToken;
  117. reslove(data)
  118. })
  119. }
  120. export function isValidKey(key: string | number | symbol, object: object): key is keyof typeof object {
  121. return key in object;
  122. }
  123. /**
  124. * 上传图片
  125. * @pic_arr {Array} 图片数组
  126. * @return {Array}
  127. */
  128. export function upLoadImage(options: { files: string[]; formData?: {}; url: string; name: string; }): Promise<any> {
  129. const _type = getDataType(options.files);
  130. options.formData = options.formData || {};
  131. const formData = {
  132. user_id: wx.getStorageSync('userId'),
  133. user_token: wx.getStorageSync('userToken'),
  134. userId: wx.getStorageSync('userId'),
  135. userid: wx.getStorageSync('userId'),
  136. userToken: wx.getStorageSync('userToken'),
  137. ...options.formData
  138. };
  139. console.log('upLoadImage=>', formData);
  140. wx.showLoading({
  141. mask: true,
  142. title: '上传中...'
  143. })
  144. return new Promise(async (resolve, reject) => {
  145. if (_type === "Array") {
  146. const _arr: string[] = [];
  147. const _files = options.files;
  148. const _len = _files.length - 1;
  149. const _url: string = await getUrl(options.url);
  150. _files.forEach((val: string, key: number) => {
  151. wx.uploadFile({
  152. url: _url,
  153. filePath: val,
  154. name: options.name,
  155. formData,
  156. success: res => {
  157. if (res.statusCode === 200) {
  158. const data = JSON.parse(res.data);
  159. console.log(data);
  160. if (data.errcode === 0) {
  161. _arr.push(data.data);
  162. if (_len === key) {
  163. wx.hideLoading()
  164. resolve(_arr)
  165. }
  166. } else {
  167. wx.showToast({
  168. title: data.message || data.errmsg,
  169. icon: 'none'
  170. })
  171. reject({
  172. type: getDataType(val)
  173. })
  174. wx.hideLoading()
  175. return false
  176. }
  177. }
  178. },
  179. fail: (e: any) => {
  180. console.log(e)
  181. reject({
  182. type: getDataType(val)
  183. })
  184. wx.hideLoading()
  185. throw new Error(e)
  186. }
  187. })
  188. })
  189. } else {
  190. reject({
  191. type: _type
  192. })
  193. wx.hideLoading()
  194. throw new Error('输入格式有误')
  195. }
  196. })
  197. }
  198. /**
  199. * 获取用户信息
  200. */
  201. export function getHwUserInfo(): AnyObject {
  202. return new Promise(resolve => {
  203. getHwUserInfoApi().then(data => {
  204. const res = <responseOptionsType>data
  205. if (res.data) {
  206. //成功后存入缓存
  207. wx.setStorageSync('userInfo', res.data.hwUser);
  208. resolve(res.data.hwUser)
  209. }
  210. }).catch(error => {
  211. console.error(error);
  212. })
  213. })
  214. }
  215. /**
  216. * 设置可过期的缓存
  217. * @param key
  218. * @param value
  219. * @param time
  220. */
  221. export function putStorageSync(key: string, value: any, time: number = 86400000): void {
  222. wx.setStorageSync(key, value)
  223. const _time: number = Date.now()
  224. wx.setStorageSync(key + 'redis', _time + time)
  225. }
  226. /**
  227. * 获取可过期缓存
  228. * @param key
  229. */
  230. export function getStorageSync(key: string): any {
  231. const time: number = wx.getStorageSync(key + 'redis')
  232. if (!time || Date.now() > time) {
  233. wx.removeStorageSync(key)
  234. wx.removeStorageSync(key + 'redis')
  235. return ''
  236. } else {
  237. return wx.getStorageSync(key)
  238. }
  239. }
  240. /**
  241. * 获取隐私协议信息
  242. */
  243. export function getPrivacySetting():Promise<{needAuthorization:boolean,privacyContractName:string}> {
  244. return new Promise(resolve=>{
  245. if (wx.canIUse('getPrivacySetting')) {
  246. wx.getPrivacySetting({
  247. success(res){
  248. resolve(res)
  249. }
  250. })
  251. }else{
  252. resolve({
  253. needAuthorization:false,
  254. privacyContractName:''
  255. })
  256. }
  257. })
  258. }