index.js 4.5 KB
Newer Older
雪洛's avatar
雪洛 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
import {
  wrapFn
} from './common/wrap-fn'
import messages from './lang/index'

import * as methodList from './uni-id'

function parseContext (context) {
  return {
    appId: context.APPID,
    platform: context.PLATFORM,
    locale: context.LOCALE,
    clientIP: context.CLIENTIP,
    deviceId: context.DEVICEID
  }
}

const uniIDConfig = require('uni-config-center')({
  pluginId: 'uni-id'
})

class UniID {
  constructor ({
    context,
    clientInfo,
    config
  } = {}) {
    this._clientInfo = context ? parseContext(context) : clientInfo
29 30
    this._config = config
    this.config = this._getOriginConfig()
雪洛's avatar
雪洛 已提交
31 32 33 34
    this.interceptorMap = new Map()
    if (uniIDConfig.hasFile('custom-token.js')) {
      this.setInterceptor('customToken', require(uniIDConfig.resolve('custom-token.js')))
    }
雪洛's avatar
雪洛 已提交
35
    const fallbackLocale = 'zh-Hans'
雪洛's avatar
雪洛 已提交
36 37
    this._i18n = uniCloud.initI18n({
      locale: this._clientInfo.locale,
雪洛's avatar
雪洛 已提交
38 39
      fallbackLocale,
      messages: JSON.parse(JSON.stringify(messages))
雪洛's avatar
雪洛 已提交
40
    })
雪洛's avatar
雪洛 已提交
41 42 43
    if (!messages[this._i18n.locale]) {
      this._i18n.setLocale(fallbackLocale)
    }
雪洛's avatar
雪洛 已提交
44 45
  }

雪洛's avatar
雪洛 已提交
46 47 48 49
  setInterceptor (timing, handler) {
    this.interceptorMap.set(timing, handler)
  }

雪洛's avatar
雪洛 已提交
50 51 52 53
  _t (...args) {
    return this._i18n.t(...args)
  }

54 55 56 57 58 59 60 61
  _parseOriginConfig (configContent) {
    // require [1,2] => {0:1,1:2}
    if (Array.isArray(configContent)) {
      return configContent
    }
    return configContent[0] ? Object.values(configContent) : configContent
  }

雪洛's avatar
雪洛 已提交
62
  _getOriginConfig () {
63 64 65
    if (this._config) {
      return this._config
    }
雪洛's avatar
雪洛 已提交
66 67 68 69 70
    if (uniIDConfig.hasFile('config.json')) {
      let configContent
      try {
        configContent = uniIDConfig.config()
      } catch (error) {
71
        throw new Error('Invalid uni-id config file\n' + error.message)
雪洛's avatar
雪洛 已提交
72
      }
73
      return this._parseOriginConfig(configContent)
雪洛's avatar
雪洛 已提交
74
    } else {
75 76 77 78 79 80 81
      try {
        return this._parseOriginConfig(
          require('uni-id/config.json') // 兼容uni-id下配置文件
        )
      } catch (error) {
        throw new Error('Invalid uni-id config file')
      }
雪洛's avatar
雪洛 已提交
82 83 84 85 86 87 88 89
    }
  }

  _getAppConfig () {
    const originConfig = this._getOriginConfig()
    if (!Array.isArray(originConfig)) {
      return originConfig
    }
雪洛's avatar
雪洛 已提交
90
    return originConfig.find(item => item.dcloudAppid === this._clientInfo.appId) || originConfig.find(item => item.isDefaultConfig)
雪洛's avatar
雪洛 已提交
91 92 93 94
  }

  _getPlatformConfig () {
    const appConfig = this._getAppConfig()
雪洛's avatar
雪洛 已提交
95 96 97
    if (!appConfig) {
      throw new Error(`Config for current app (${this._clientInfo.appId}) was not found, please check your config file or client appId`)
    }
雪洛's avatar
雪洛 已提交
98 99 100 101 102 103
    if (this._clientInfo.platform === 'app-plus') {
      this._clientInfo.platform = 'app'
    }
    if (this._clientInfo.platform === 'h5') {
      this._clientInfo.platform = 'web'
    }
104 105 106 107 108 109 110 111 112 113 114
    let fallbackPlatform
    switch (this._clientInfo.platform) {
      case 'web':
        fallbackPlatform = 'h5'
        break
      case 'app':
        fallbackPlatform = 'app-plus'
        break
      default:
        break
    }
雪洛's avatar
雪洛 已提交
115 116 117 118 119 120
    const defaultConfig = {
      tokenExpiresIn: 7200,
      tokenExpiresThreshold: 1200,
      passwordErrorLimit: 6,
      passwordErrorRetryTime: 3600
    }
雪洛's avatar
雪洛 已提交
121
    const argsRequired = ['tokenSecret', 'tokenExpiresIn']
122 123 124 125 126 127
    const configList = [defaultConfig, appConfig]
    if (fallbackPlatform && appConfig[fallbackPlatform]) {
      configList.push(appConfig[fallbackPlatform])
    }
    configList.push(appConfig[this._clientInfo.platform])
    const config = Object.assign(...configList)
雪洛's avatar
雪洛 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    argsRequired.forEach((item) => {
      if (!config || !config[item]) {
        throw new Error(`Config parameter missing, ${item} is required`)
      }
    })
    return config
  }

  _getConfig () {
    return this._getPlatformConfig()
  }
}

for (const key in methodList) {
  UniID.prototype[key] = methodList[key]
}

function createInstance (params) {
  // {
  //   context,
  //   clientInfo,
  //   config
  // } = params
  const uniIDOrigin = new UniID(params)
  const uniID = new Proxy(uniIDOrigin, {
    get (target, prop) {
      if (prop in target && prop.indexOf('_') !== 0) {
        if (typeof target[prop] === 'function') {
          return wrapFn(target[prop]).bind(target)
        } else if (prop === 'context' || prop === 'config') {

        } else {
          return target[prop]
        }
      }
    }
  })
  return uniID
}

UniID.prototype.createInstance = createInstance

const uniID = {
  // 自4.0.0版起只能使用createInstance创建实例,直接require('uni-id')仅会得到一个包含createInstance方法的对象
  createInstance
}

export default uniID