config.js 1.6 KB
Newer Older
雪洛's avatar
雪洛 已提交
1 2 3 4 5
'use strict';

const configCenter = require('uni-config-center')

const OauthConfig = {
雪洛's avatar
雪洛 已提交
6 7
  'mp-weixin': ['mp-weixin', 'oauth', 'weixin'],
  'h5-weixin': ['web', 'oauth', 'h5-weixin']
雪洛's avatar
雪洛 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
}

class ConfigBase {

  constructor() {
    this._ready = false
    this._uniId = null

    const uniIdConfig = configCenter({
      pluginId: 'uni-id'
    })

    this._uniId = uniIdConfig.config()

    this._ready = true
  }

  getAppConfig(appid) {
    if (Array.isArray(this._uniId)) {
      return this._uniId.find((item) => {
        return (item.dcloudAppid === appid)
      })
    }
雪洛's avatar
雪洛 已提交
31
    return this._uniId
雪洛's avatar
雪洛 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
  }

  get ready() {
    return this._ready
  }
}

class AppConfig extends ConfigBase {

  constructor() {
    super()
  }

  get(appid, platform) {
    if (!this.isSupport(platform)) {
      return null
    }

    let appConfig = this.getAppConfig(appid)
    if (!appConfig) {
      return null
    }

55
    return this.getOauthConfig(appConfig, platform)
雪洛's avatar
雪洛 已提交
56 57 58 59 60 61 62 63
  }

  isSupport(platformName) {
    return (AppConfig.Support_Platforms.indexOf(platformName) >= 0)
  }

  getOauthConfig(appConfig, platformName) {
    let tree = OauthConfig[platformName]
雪洛's avatar
雪洛 已提交
64
    let node = appConfig
雪洛's avatar
雪洛 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    for (let i = 0; i < tree.length; i++) {
      let nodeName = tree[i]
      if (node[nodeName]) {
        node = node[nodeName]
      } else {
        node = null
        break
      }
    }

    if (node && node.appid && node.appsecret) {
      return {
        appid: node.appid,
        secret: node.appsecret
      }
    }

    return null
  }
}

AppConfig.Support_Platforms = ['mp-weixin', 'h5-weixin']


module.exports = {
  AppConfig
};