register.js 2.0 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 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 92 93
const url = require('url')
const { preRegister, postRegister } = require('../../lib/utils/register')
const { EXTERNAL_DIRECT_CONNECT_PROVIDER } = require('../../common/constants')

/**
 * 外部注册用户
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#external-register
 * @param {object} params
 * @param {string} params.externalUid   业务系统的用户id
 * @param {string} params.nickname  昵称
 * @param {number} params.gender  性别
 * @param {string} params.avatar  头像
 * @returns {object}
 */
module.exports = async function (params = {}) {
  const schema = {
    externalUid: 'string',
    nickname: {
      required: false,
      type: 'nickname'
    },
    gender: {
      required: false,
      type: 'number'
    },
    avatar: {
      required: false,
      type: 'string'
    }
  }

  this.middleware.validate(params, schema)

  const {
    externalUid,
    avatar,
    gender,
    nickname
  } = params

  await preRegister.call(this, {
    user: {
      identities: {
        provider: EXTERNAL_DIRECT_CONNECT_PROVIDER,
        uid: externalUid
      }
    }
  })

  const extraData = {}

  if (avatar) {
    // eslint-disable-next-line n/no-deprecated-api
    const avatarPath = url.parse(avatar).pathname
    const extName = avatarPath.indexOf('.') > -1 ? avatarPath.split('.').pop() : ''

    extraData.avatar_file = {
      name: avatarPath,
      extname: extName,
      url: avatar
    }
  }

  const result = await postRegister.call(this, {
    user: {
      avatar,
      gender,
      nickname,
      identities: [
        {
          provider: EXTERNAL_DIRECT_CONNECT_PROVIDER,
          userInfo: {
            avatar,
            gender,
            nickname
          },
          uid: externalUid
        }
      ]
    },
    extraData
  })

  return {
    errCode: result.errCode,
    newToken: result.newToken,
    externalUid,
    avatar,
    gender,
    nickname,
    uid: result.uid
  }
}