universal.js 1.3 KB
Newer Older
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
const { ERROR } = require('./error')

function getHttpClientInfo () {
  const requestId = this.getUniCloudRequestId()
  const { clientIP, userAgent, source, secretType = 'none' } = this.getClientInfo()
  const { clientInfo = {} } = JSON.parse(this.getHttpInfo().body)

  return {
    ...clientInfo,
    clientIP,
    userAgent,
    source,
    secretType,
    requestId
  }
}

function getHttpUniIdToken () {
  const { uniIdToken = '' } = JSON.parse(this.getHttpInfo().body)

  return uniIdToken
}

function verifyHttpMethod () {
  const { headers, httpMethod } = this.getHttpInfo()

  if (!/^application\/json/.test(headers['content-type']) || httpMethod.toUpperCase() !== 'POST') {
    throw {
      errCode: ERROR.UNSUPPORTED_REQUEST,
      errMsg: 'unsupported request'
    }
  }
}

function universal () {
  if (this.getClientInfo().source === 'http') {
    verifyHttpMethod.call(this)
    this.getParams()[0] = JSON.parse(this.getHttpInfo().body).params
    this.getUniversalClientInfo = getHttpClientInfo.bind(this)
    this.getUniversalUniIdToken = getHttpUniIdToken.bind(this)
  } else {
    this.getUniversalClientInfo = this.getClientInfo
    this.getUniversalUniIdToken = this.getUniIdToken
  }
}

module.exports = universal