import { isObject } from "@/utils/is"; // import { SharePosterGetShareInfo } from '@/api' /** * 对象转字符串 * { a: 1, b: 2 } ==> a=1&b=2 */ export function objectTOString(obj, options) { const { separator = '&' } = options || {} if(!isObject(obj)) return ''; const arr = [] for (let key in obj) { let str = [key,obj[key]].join('=') arr.push(str) } return arr.join(separator) } /** * 字符串转对象 * a=1&b=2 ==> { a: 1, b: 2} * a = 1& b =2 ==> { a: 1, b: 2} */ export function stringToObject(str, options){ if(!str) return {} const { separator = '&' } = options || {} str = decodeURI(str) const obj = {} const keys = str.split(separator) keys.forEach((key) => { const [k, v] = key.split('='); obj[k.trim()] = v.trim(); }); return obj; } export const SHARE_ID = 'sharerID' // 后端定义的 const cacheProfix = 'share_' // 缓存前缀 const cacheKeys = [SHARE_ID] // 需要缓存的keys const getCacheKey = (key) => cacheProfix + key export function useShare() { // 获取识别二维码的信息 async function formatShareInfo(id) { return try { let { data } = await SharePosterGetShareInfo({ id }) console.log('data', data) // const data = 'shareId=X&id=xx' const param = stringToObject(data.search) // 需要缓存起来的key for (let key of cacheKeys) { const time = Date.now() if(param[key]){ uni.setStorageSync(getCacheKey(key), { time, // 存储时间 expire: time + 1000 * 60 * 60 * 24 * 1, // 过期时间 1代表一天 value: param[key] || '' }) delete param[key] } } return Promise.resolve(param) } catch (error) { //TODO handle the exception } } // 通过key获取指定缓存 function getShareInfo(key){ const cacheKey = getCacheKey(key) const storageVal = uni.getStorageSync(cacheKey); const nowTime = Date.now() if(storageVal){ if(nowTime < storageVal.expire){ return storageVal.value } uni.removeStorageSync(cacheKey) } return "" } // return { formatShareInfo, getShareInfo } }