hook.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { isObject } from "@/utils/is";
  2. // import { SharePosterGetShareInfo } from '@/api'
  3. /**
  4. * 对象转字符串
  5. * { a: 1, b: 2 } ==> a=1&b=2
  6. */
  7. export function objectTOString(obj, options) {
  8. const { separator = '&' } = options || {}
  9. if(!isObject(obj)) return '';
  10. const arr = []
  11. for (let key in obj) {
  12. let str = [key,obj[key]].join('=')
  13. arr.push(str)
  14. }
  15. return arr.join(separator)
  16. }
  17. /**
  18. * 字符串转对象
  19. * a=1&b=2 ==> { a: 1, b: 2}
  20. * a = 1& b =2 ==> { a: 1, b: 2}
  21. */
  22. export function stringToObject(str, options){
  23. if(!str) return {}
  24. const { separator = '&' } = options || {}
  25. str = decodeURI(str)
  26. const obj = {}
  27. const keys = str.split(separator)
  28. keys.forEach((key) => {
  29. const [k, v] = key.split('=');
  30. obj[k.trim()] = v.trim();
  31. });
  32. return obj;
  33. }
  34. export const SHARE_ID = 'sharerID' // 后端定义的
  35. const cacheProfix = 'share_' // 缓存前缀
  36. const cacheKeys = [SHARE_ID] // 需要缓存的keys
  37. const getCacheKey = (key) => cacheProfix + key
  38. export function useShare() {
  39. // 获取识别二维码的信息
  40. async function formatShareInfo(id) {
  41. return
  42. try {
  43. let { data } = await SharePosterGetShareInfo({ id })
  44. console.log('data', data)
  45. // const data = 'shareId=X&id=xx'
  46. const param = stringToObject(data.search)
  47. // 需要缓存起来的key
  48. for (let key of cacheKeys) {
  49. const time = Date.now()
  50. if(param[key]){
  51. uni.setStorageSync(getCacheKey(key), {
  52. time, // 存储时间
  53. expire: time + 1000 * 60 * 60 * 24 * 1, // 过期时间 1代表一天
  54. value: param[key] || ''
  55. })
  56. delete param[key]
  57. }
  58. }
  59. return Promise.resolve(param)
  60. } catch (error) {
  61. //TODO handle the exception
  62. }
  63. }
  64. // 通过key获取指定缓存
  65. function getShareInfo(key){
  66. const cacheKey = getCacheKey(key)
  67. const storageVal = uni.getStorageSync(cacheKey);
  68. const nowTime = Date.now()
  69. if(storageVal){
  70. if(nowTime < storageVal.expire){
  71. return storageVal.value
  72. }
  73. uni.removeStorageSync(cacheKey)
  74. }
  75. return ""
  76. }
  77. //
  78. return { formatShareInfo, getShareInfo }
  79. }