index.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. const Db = require('@cloudbase/database').Db
  2. const storage = require('./src/storage')
  3. const functions = require('./src/functions')
  4. const auth = require('./src/auth')
  5. const wx = require('./src/wx')
  6. const Request = require('./src/utils/dbRequest')
  7. const logger = require('./src/log')
  8. const { SYMBOL_CURRENT_ENV } = require('./src/const/symbol')
  9. const { getCurrentEnv } = require('./src/utils/utils')
  10. const ExtRequest = require('./src/utils/extRequest')
  11. function Tcb(config) {
  12. this.config = config ? config : this.config
  13. this.requestClient = new ExtRequest()
  14. this.SYMBOL_CURRENT_ENV = SYMBOL_CURRENT_ENV
  15. }
  16. Tcb.prototype.init = function({
  17. secretId,
  18. secretKey,
  19. sessionToken,
  20. debug,
  21. env,
  22. proxy,
  23. timeout,
  24. serviceUrl,
  25. version,
  26. headers = {},
  27. credentials,
  28. timingsMeasurer,
  29. isHttp,
  30. signMethod = 'v2',
  31. isUpdateSelfConfig = true,
  32. forever = false
  33. } = {}) {
  34. if ((secretId && !secretKey) || (!secretId && secretKey)) {
  35. throw Error('secretId and secretKey must be a pair')
  36. }
  37. const config = {
  38. get secretId() {
  39. return this._secretId ? this._secretId : process.env.TENCENTCLOUD_SECRETID
  40. },
  41. set secretId(id) {
  42. this._secretId = id
  43. },
  44. get secretKey() {
  45. return this._secretKey
  46. ? this._secretKey
  47. : process.env.TENCENTCLOUD_SECRETKEY
  48. },
  49. set secretKey(key) {
  50. this._secretKey = key
  51. },
  52. get sessionToken() {
  53. if (this._sessionToken === undefined) {
  54. //默认临时密钥
  55. return process.env.TENCENTCLOUD_SESSIONTOKEN
  56. } else if (this._sessionToken === false) {
  57. //固定秘钥
  58. return undefined
  59. } else {
  60. //传入的临时密钥
  61. return this._sessionToken
  62. }
  63. },
  64. set sessionToken(token) {
  65. this._sessionToken = token
  66. },
  67. envName: env,
  68. proxy: proxy,
  69. isHttp: isHttp,
  70. headers: Object.assign({}, headers)
  71. }
  72. config.debug = debug
  73. config.forever = forever
  74. config.signMethod = signMethod
  75. config.timingsMeasurer = timingsMeasurer
  76. config.secretId = secretId
  77. config.secretKey = secretKey
  78. config.timeout = timeout || 15000
  79. config.serviceUrl = serviceUrl
  80. config.credentials = credentials
  81. config.sessionToken = sessionToken
  82. ? sessionToken
  83. : secretId && secretKey
  84. ? false
  85. : undefined
  86. if (version) {
  87. config.headers['x-sdk-version'] = version
  88. }
  89. // 这里的目的是创建新实例时可以避免更新当前实例
  90. if (isUpdateSelfConfig) {
  91. this.config = config
  92. }
  93. return new Tcb(config)
  94. }
  95. Tcb.prototype.database = function(dbConfig = {}) {
  96. Db.reqClass = Request
  97. if (Object.prototype.toString.call(dbConfig).slice(8, -1) !== 'Object') {
  98. throw Error('dbConfig must be an object')
  99. }
  100. if (dbConfig && dbConfig.env) {
  101. // env变量名转换
  102. dbConfig.envName = dbConfig.env
  103. delete dbConfig.env
  104. }
  105. this.config = Object.assign(this.config, dbConfig)
  106. return new Db({ ...this })
  107. }
  108. /**
  109. * @returns string
  110. */
  111. Tcb.prototype.getCurrentEnv = function() {
  112. return getCurrentEnv()
  113. }
  114. const extensionMap = {}
  115. /**
  116. * 注册扩展
  117. */
  118. Tcb.prototype.registerExtension = function(ext) {
  119. extensionMap[ext.name] = ext
  120. }
  121. Tcb.prototype.invokeExtension = async function(name, opts) {
  122. const ext = extensionMap[name]
  123. if (!ext) {
  124. throw Error(`扩展${name} 必须先注册`)
  125. }
  126. return await ext.invoke(opts, this)
  127. }
  128. Tcb.prototype.parseContext = function(context) {
  129. if (typeof context !== 'object') {
  130. throw Error('context 必须为对象类型')
  131. }
  132. let {
  133. memory_limit_in_mb,
  134. time_limit_in_ms,
  135. request_id,
  136. environ = '',
  137. function_version,
  138. namespace,
  139. function_name,
  140. environment
  141. } = context
  142. let parseResult = {}
  143. try {
  144. parseResult.memoryLimitInMb = memory_limit_in_mb
  145. parseResult.timeLimitIns = time_limit_in_ms
  146. parseResult.requestId = request_id
  147. parseResult.functionVersion = function_version
  148. parseResult.namespace = namespace
  149. parseResult.functionName = function_name
  150. // 存在environment 为新架构 上新字段 JSON序列化字符串
  151. if (environment) {
  152. parseResult.environment = JSON.parse(environment)
  153. return parseResult
  154. }
  155. // 不存在environment 则为老字段,老架构上存在bug,无法识别value含特殊字符(若允许特殊字符,影响解析,这里特殊处理)
  156. const parseEnviron = environ.split(';')
  157. let parseEnvironObj = {}
  158. for (let i in parseEnviron) {
  159. const equalIndex = parseEnviron[i].indexOf('=')
  160. if (equalIndex < 0) {
  161. // value含分号影响切割,未找到= 均忽略
  162. continue
  163. }
  164. const key = parseEnviron[i].slice(0, equalIndex)
  165. let value = parseEnviron[i].slice(equalIndex + 1)
  166. // value 含, 为数组
  167. if (value.indexOf(',') >= 0) {
  168. value = value.split(',')
  169. }
  170. parseEnvironObj[key] = value
  171. }
  172. parseResult.environ = parseEnvironObj
  173. } catch (err) {
  174. throw Error('无效的context对象')
  175. }
  176. return parseResult
  177. }
  178. function each(obj, fn) {
  179. for (var i in obj) {
  180. if (obj.hasOwnProperty(i)) {
  181. fn(obj[i], i)
  182. }
  183. }
  184. }
  185. function extend(target, source) {
  186. each(source, function(val, key) {
  187. target[key] = source[key]
  188. })
  189. return target
  190. }
  191. extend(Tcb.prototype, functions)
  192. extend(Tcb.prototype, storage)
  193. extend(Tcb.prototype, wx)
  194. extend(Tcb.prototype, auth)
  195. extend(Tcb.prototype, logger)
  196. module.exports = new Tcb()