@cloudbase/node-sdk
Version:
tencent cloud base server sdk for node.js
310 lines (309 loc) • 14.1 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CloudBase = void 0;
const axios_1 = __importDefault(require("axios"));
const wx_cloud_client_sdk_1 = __importDefault(require("@cloudbase/wx-cloud-client-sdk"));
const auth_1 = require("./auth");
const functions_1 = require("./functions");
const cloudrun_1 = require("./cloudrun");
const database_1 = require("./database");
const storage_1 = require("./storage");
const wx_1 = require("./wx");
const analytics_1 = require("./analytics");
const logger_1 = require("./logger");
const code_1 = require("./const/code");
const utils = __importStar(require("./utils/utils"));
const cloudplatform_1 = require("./utils/cloudplatform");
const tcbcontext_1 = require("./utils/tcbcontext");
const notification_1 = require("./notification");
const openapicommonrequester = __importStar(require("./utils/tcbopenapicommonrequester"));
const tcbopenapiendpoint_1 = require("./utils/tcbopenapiendpoint");
const symbol_1 = require("./const/symbol");
class CloudBase {
static parseContext(context) {
const parseResult = (0, tcbcontext_1.parseContext)(context);
CloudBase.scfContext = parseResult;
return parseResult;
}
static getCloudbaseContext(context) {
return (0, tcbcontext_1.getCloudbaseContext)(context);
}
constructor(config) {
this.init(config);
}
init(config = {}) {
var _a, _b, _c, _d;
// 预检运行环境,调用与否并不影响后续逻辑
// 注意:该函数为异步函数,这里并不等待检查结果
/* eslint-disable-next-line */
(0, cloudplatform_1.preflightRuntimeCloudPlatform)();
const { debug, secretId, secretKey, sessionToken, env, timeout, headers = {} } = config, restConfig = __rest(config, ["debug", "secretId", "secretKey", "sessionToken", "env", "timeout", "headers"]);
if (('secretId' in config && !('secretKey' in config))
|| (!('secretId' in config) && 'secretKey' in config)) {
throw utils.E(Object.assign(Object.assign({}, code_1.ERROR.INVALID_PARAM), { message: 'secretId and secretKey must be a pair' }));
}
const newConfig = Object.assign(Object.assign({}, restConfig), { debug: !!debug, secretId,
secretKey,
sessionToken,
env, envName: env, headers: Object.assign({}, headers), timeout: timeout || 15000 });
if ((_a = config.context) === null || _a === void 0 ? void 0 : _a.extendedContext) {
const extendedContext = config.context.extendedContext;
if (!newConfig.env) {
newConfig.env = extendedContext.envId;
newConfig.envName = newConfig.env;
}
// 从 context 中获取 secret
if (!newConfig.secretId && !newConfig.secretKey) {
newConfig.secretId = (_b = extendedContext === null || extendedContext === void 0 ? void 0 : extendedContext.tmpSecret) === null || _b === void 0 ? void 0 : _b.secretId;
newConfig.secretKey = (_c = extendedContext === null || extendedContext === void 0 ? void 0 : extendedContext.tmpSecret) === null || _c === void 0 ? void 0 : _c.secretKey;
newConfig.sessionToken = (_d = extendedContext === null || extendedContext === void 0 ? void 0 : extendedContext.tmpSecret) === null || _d === void 0 ? void 0 : _d.token;
}
}
this.config = newConfig;
this.extensionMap = new Map();
// NOTE:try-catch 为防止 init 报错
try {
// 初始化数据模型等 SDK 方法
const envId = this.config.envName === symbol_1.SYMBOL_CURRENT_ENV
? openapicommonrequester.getEnvIdFromContext()
: this.config.envName;
const httpClient = wx_cloud_client_sdk_1.default.generateHTTPClient(this.callFunction.bind(this), async (options) => {
var _a;
const result = await openapicommonrequester.request({
config: this.config,
data: safeParseJSON(options.body),
method: (_a = options.method) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
url: options.url,
headers: Object.assign({ 'Content-Type': 'application/json' }, headersInitToRecord(options.headers)),
token: (await this.auth().getClientCredential()).access_token
});
return result.body;
}, (0, tcbopenapiendpoint_1.buildCommonOpenApiUrlWithPath)({ serviceUrl: this.config.serviceUrl, envId, path: '/v1/model', region: this.config.region }), {
sqlBaseUrl: (0, tcbopenapiendpoint_1.buildCommonOpenApiUrlWithPath)({ serviceUrl: this.config.serviceUrl, envId, path: '/v1/sql', region: this.config.region })
});
this.models = httpClient;
}
catch (e) {
// ignore
}
try {
const getEntity = (options) => {
const envId = this.config.envName === symbol_1.SYMBOL_CURRENT_ENV
? openapicommonrequester.getEnvIdFromContext()
: this.config.envName;
const { instance = 'default', database = envId } = options || {};
const mysqlClient = wx_cloud_client_sdk_1.default.generateMySQLClient(this, {
mysqlBaseUrl: (0, tcbopenapiendpoint_1.buildCommonOpenApiUrlWithPath)({
serviceUrl: this.config.serviceUrl,
envId,
path: '/v1/rdb/rest',
region: this.config.region
}),
fetch: async (url, options) => {
var _a;
let headers = {};
if (options.headers instanceof Headers) {
options.headers.forEach((value, key) => {
headers[key] = value;
});
}
else {
headers = options.headers || {};
}
const result = await openapicommonrequester.request({
config: this.config,
data: safeParseJSON(options.body),
method: (_a = options.method) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
url: url instanceof URL ? url.href : String(url),
headers: Object.assign({ 'Content-Type': 'application/json' }, headersInitToRecord(Object.assign({ 'X-Db-Instance': instance, 'Accept-Profile': database, 'Content-Profile': database }, headers))),
token: (await this.auth().getClientCredential()).access_token
});
const data = result.body;
const res = {
ok: (result === null || result === void 0 ? void 0 : result.statusCode) >= 200 && (result === null || result === void 0 ? void 0 : result.statusCode) < 300,
status: (result === null || result === void 0 ? void 0 : result.statusCode) || 200,
statusText: (result === null || result === void 0 ? void 0 : result.statusMessage) || 'OK',
json: async () => await Promise.resolve(data || {}),
text: async () => await Promise.resolve(typeof data === 'string' ? data : JSON.stringify(data || {})),
headers: new Headers((result === null || result === void 0 ? void 0 : result.headers) || {})
};
return res;
}
});
return mysqlClient;
};
this.mysql = (options) => {
return getEntity(options)(options);
};
}
catch (e) {
// ignore
}
}
logger() {
if (!this.clsLogger) {
this.clsLogger = (0, logger_1.logger)();
}
return this.clsLogger;
}
auth() {
return (0, auth_1.auth)(this);
}
database(dbConfig = {}) {
return (0, database_1.newDb)(this, dbConfig);
}
async callFunction(callFunctionOptions, opts) {
return await (0, functions_1.callFunction)(this, callFunctionOptions, opts);
}
async callContainer(callContainerOptions, opts) {
return await (0, cloudrun_1.callContainer)(this, callContainerOptions, opts);
}
async callApis(callApiOptions, opts) {
return await (0, functions_1.callApis)(this, callApiOptions, opts);
}
async callWxOpenApi(wxOpenApiOptions, opts) {
return await (0, wx_1.callWxOpenApi)(this, wxOpenApiOptions, opts);
}
async callWxPayApi(wxOpenApiOptions, opts) {
return await (0, wx_1.callWxPayApi)(this, wxOpenApiOptions, opts);
}
async wxCallContainerApi(wxOpenApiOptions, opts) {
return await (0, wx_1.wxCallContainerApi)(this, wxOpenApiOptions, opts);
}
async callCompatibleWxOpenApi(wxOpenApiOptions, opts) {
return await (0, wx_1.callCompatibleWxOpenApi)(this, wxOpenApiOptions, opts);
}
async uploadFile({ cloudPath, fileContent }, opts) {
return await (0, storage_1.uploadFile)(this, { cloudPath, fileContent }, opts);
}
async downloadFile({ fileID, urlType, tempFilePath }, opts) {
return await (0, storage_1.downloadFile)(this, { fileID, urlType, tempFilePath }, opts);
}
/**
* 复制文件
*
* @param fileList 复制列表
* @param fileList.srcPath 源文件路径
* @param fileList.dstPath 目标文件路径
* @param fileList.overwrite 当目标文件已经存在时,是否允许覆盖已有文件,默认 true
* @param fileList.removeOriginal 复制文件后是否删除源文件,默认不删除
* @param opts
*/
async copyFile({ fileList }, opts) {
return await (0, storage_1.copyFile)(this, { fileList }, opts);
}
async deleteFile({ fileList }, opts) {
return await (0, storage_1.deleteFile)(this, { fileList }, opts);
}
async getTempFileURL({ fileList }, opts) {
return await (0, storage_1.getTempFileURL)(this, { fileList }, opts);
}
async getFileInfo({ fileList }, opts) {
return await (0, storage_1.getFileInfo)(this, { fileList }, opts);
}
async getUploadMetadata({ cloudPath }, opts) {
return await (0, storage_1.getUploadMetadata)(this, { cloudPath }, opts);
}
async getFileAuthority({ fileList }, opts) {
return await (0, storage_1.getFileAuthority)(this, { fileList }, opts);
}
/**
* @deprecated
*/
async analytics(reportData) {
await (0, analytics_1.analytics)(this, reportData);
}
registerExtension(ext) {
this.extensionMap.set(ext.name, ext);
}
async invokeExtension(name, opts) {
const ext = this.extensionMap.get(name);
if (!ext) {
throw Error(`Please register '${name}' extension before invoke.`);
}
return ext.invoke(opts, this);
}
// SDK推送消息(对外API:sendTemplateNotification)
async sendTemplateNotification(params, opts) {
return await (0, notification_1.sendNotification)(this, params, opts);
}
/**
* shim for tcb extension ci
*/
get requestClient() {
return {
get: axios_1.default,
post: axios_1.default,
put: axios_1.default,
delete: axios_1.default
};
}
}
exports.CloudBase = CloudBase;
function headersInitToRecord(headers) {
if (!headers) {
return {};
}
const ret = {};
if (Array.isArray(headers)) {
headers.forEach(([key, value]) => {
ret[key] = value;
});
}
else if (typeof headers.forEach === 'function') {
headers.forEach(([key, value]) => {
ret[key] = value;
});
}
else {
Object.keys(headers).forEach(key => {
ret[key] = headers[key];
});
}
return ret;
}
function safeParseJSON(x) {
try {
return JSON.parse(x);
}
catch (e) {
return x;
}
}