@cloudbase/node-sdk
Version:
tencent cloud base server sdk for node.js
309 lines (308 loc) • 13.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 __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 ai_1 = require("./ai");
const logger_1 = require("./logger");
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");
const utils_1 = require("./utils/utils");
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 = {}) {
// 预检运行环境,调用与否并不影响后续逻辑
// 注意:该函数为异步函数,这里并不等待检查结果
/* eslint-disable-next-line */
(0, cloudplatform_1.preflightRuntimeCloudPlatform)();
// 所有的鉴权,参数塑形都在 normalizeConfig 中处理
// 后续其他模块获取 config 都通过 CloudBase 实例的 config 获取
// 禁止在业务模块中直接修改 config 配置
this.config = (0, utils_1.normalizeConfig)(config);
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)),
/**
* 既然 openapicommonrequester.request 的参数里的 token 获取也是通过 openapicommonrequester.request 方法去获取的
* 为什么不把这里的 token 去掉,全部放在 openapicommonrequester.request 中去统一处理 token 获取的逻辑
*/
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(incomingHttpHeadersToHeadersInit((result === null || result === void 0 ? void 0 : result.headers) || {}))
};
return res;
}
});
return mysqlClient;
};
this.mysql = (options) => {
return getEntity(options)(options);
};
this.rdb = (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);
}
ai() {
if (!this.aiInstance) {
this.aiInstance = (0, ai_1.createAI)(this);
}
return this.aiInstance;
}
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;
}
}
function incomingHttpHeadersToHeadersInit(headers) {
const result = [];
for (const [key, value] of Object.entries(headers)) {
if (value === undefined) {
continue;
}
if (Array.isArray(value)) {
for (const v of value) {
result.push([key, v]);
}
}
else {
result.push([key, value]);
}
}
return result;
}