push.js 2.3 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11
import {
  isFn,
  isPlainObject
} from 'uni-shared'
import {
  getApiCallbacks
} from 'uni-helpers/utils'

let cid
let cidErrMsg

12
function normalizePushMessage (message) {
fxy060608's avatar
fxy060608 已提交
13
  try {
14
    return JSON.parse(message)
fxy060608's avatar
fxy060608 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
  } catch (e) {}
  return message
}

export function invokePushCallback (
  args
) {
  if (args.type === 'clientId') {
    cid = args.cid
    cidErrMsg = args.errMsg
    invokeGetPushCidCallbacks(cid, args.errMsg)
  } else if (args.type === 'pushMsg') {
    onPushMessageCallbacks.forEach((callback) => {
      callback({
        type: 'receive',
30
        data: normalizePushMessage(args.message)
fxy060608's avatar
fxy060608 已提交
31 32 33 34 35 36
      })
    })
  } else if (args.type === 'click') {
    onPushMessageCallbacks.forEach((callback) => {
      callback({
        type: 'click',
37
        data: normalizePushMessage(args.message)
fxy060608's avatar
fxy060608 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51
      })
    })
  }
}

const getPushCidCallbacks = []

function invokeGetPushCidCallbacks (cid, errMsg) {
  getPushCidCallbacks.forEach((callback) => {
    callback(cid, errMsg)
  })
  getPushCidCallbacks.length = 0
}

52
export function getPushClientId (args) {
fxy060608's avatar
fxy060608 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
  if (!isPlainObject(args)) {
    args = {}
  }
  const {
    success,
    fail,
    complete
  } = getApiCallbacks(args)
  const hasSuccess = isFn(success)
  const hasFail = isFn(fail)
  const hasComplete = isFn(complete)
  getPushCidCallbacks.push((cid, errMsg) => {
    let res
    if (cid) {
      res = {
68
        errMsg: 'getPushClientId:ok',
fxy060608's avatar
fxy060608 已提交
69 70 71 72 73
        cid
      }
      hasSuccess && success(res)
    } else {
      res = {
74
        errMsg: 'getPushClientId:fail' + (errMsg ? ' ' + errMsg : '')
fxy060608's avatar
fxy060608 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
      }
      hasFail && fail(res)
    }
    hasComplete && complete(res)
  })
  if (typeof cid !== 'undefined') {
    Promise.resolve().then(() => invokeGetPushCidCallbacks(cid, cidErrMsg))
  }
}

const onPushMessageCallbacks = []
// 不使用 defineOnApi 实现,是因为 defineOnApi 依赖 UniServiceJSBridge ,该对象目前在小程序上未提供,故简单实现
export const onPushMessage = (fn) => {
  if (onPushMessageCallbacks.indexOf(fn) === -1) {
    onPushMessageCallbacks.push(fn)
  }
}

export const offPushMessage = (fn) => {
  if (!fn) {
    onPushMessageCallbacks.length = 0
  } else {
    const index = onPushMessageCallbacks.indexOf(fn)
    if (index > -1) {
      onPushMessageCallbacks.splice(index, 1)
    }
  }
102
}