share.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * 分享工具:小程序分享(onShareAppMessage / onShareTimeline)共用逻辑。
  3. *
  4. * 邀请码(转介绍跟踪):仅登录用户有,复用 train_user.invite_code,
  5. * 经 /api/invite/myposter 惰性加载一次,按 userId 缓存(模块级 + storage)。
  6. * 未登录 / 加载失败时不带邀请码,分享仍可用。
  7. */
  8. import { getMyPoster } from '@/utils/api.js'
  9. import config from '@/config.js'
  10. let cached = { userId: '', code: '' }
  11. function currentUserId() {
  12. return uni.getStorageSync('userId') || ''
  13. }
  14. function readInviteCode() {
  15. var userId = currentUserId()
  16. if (!userId) return ''
  17. if (cached.userId === userId && cached.code) return cached.code
  18. var code = uni.getStorageSync('invite_' + userId)
  19. if (code) {
  20. cached = { userId: userId, code: code }
  21. }
  22. return cached.userId === userId ? cached.code : ''
  23. }
  24. /**
  25. * 预载当前用户邀请码(页面 onLoad/onShow 调用,不阻塞 UI、不弹登录框)。
  26. * 返回 Promise<string>:已有缓存/无登录用户时立即 resolve,供「生成海报」等
  27. * 需要邀请码才能继续的场景 await 后使用。
  28. */
  29. export function loadInviteCode() {
  30. var userId = currentUserId()
  31. if (!userId) return Promise.resolve('')
  32. var existing = readInviteCode()
  33. if (existing) return Promise.resolve(existing)
  34. return getMyPoster().then(function(resp) {
  35. var data = resp.data || {}
  36. var code = data.inviteCode || ''
  37. if (code) {
  38. cached = { userId: userId, code: code }
  39. uni.setStorageSync('invite_' + userId, code)
  40. }
  41. return code
  42. }).catch(function() {
  43. // 静默失败:分享路径不带邀请码
  44. return ''
  45. })
  46. }
  47. /** 同步读取已缓存的邀请码(onShareAppMessage / onShareTimeline 回调内使用) */
  48. export function getInviteCode() {
  49. return readInviteCode()
  50. }
  51. /** 拼分享路径:path(如 /pages/course/detail?courseId=1)末尾追加 inviteCode 参数 */
  52. export function buildSharePath(path) {
  53. var code = readInviteCode()
  54. if (!code) return path
  55. return path + (path.indexOf('?') > -1 ? '&' : '?') + 'inviteCode=' + code
  56. }
  57. /**
  58. * 后端返回的 /uploads/xxx 资源路径转绝对地址。
  59. * 小程序端 <image> / uni.getImageInfo 不能使用 / 开头的相对路径(会被当作包内本地文件),
  60. * H5 端 BASE_URL 为空时保持相对路径(由 nginx 同域提供)。
  61. */
  62. export function resolveAssetUrl(path) {
  63. if (!path) return ''
  64. if (path.indexOf('http://') === 0 || path.indexOf('https://') === 0) return path
  65. if (path.charAt(0) === '/') return config.api(path)
  66. return path
  67. }