import * as tencentcloud from "tencentcloud-sdk-nodejs";
import * as actionName from '../constants/actionName'
import {
DescribeDocumentParams,
ModifyDocumentParams,
DeleteDocumentParams,
ModifyDocumentResponse
} from '../interface/cloudApi/database'
import {
InvokeFunctionParams
} from '../interface/cloudApi/functions'
import {
GetDownloadUrlsParams,
DeleteFilesParams
} from '../interface/cloudApi/storage'
import {
CloudApiResponse,
} from '../interface/cloudApi'
const { Client, Models } = tencentcloud.tcb.v20180608;
const { Credential, ClientProfile, HttpProfile } = tencentcloud.common;
const actionMapping = {
[actionName.InvokeFunction]: 'functions',
[actionName.GetUploadFileUrl]: 'storage',
[actionName.GetDownloadUrls]: 'storage',
[actionName.DeleteFiles]: 'storage',
[actionName.CreateDocument]: 'database',
[actionName.DeleteDocument]: 'database',
[actionName.DescribeDocument]: 'database',
[actionName.ModifyDocument]: 'database',
[actionName.CreateCollection]: 'database'
}
interface tcbConfig {
secretId: string
secretKey: string
envName: string
}
interface cloudApiRequestArgs {
config: tcbConfig
params: DescribeDocumentParams | ModifyDocumentParams | DeleteDocumentParams | ModifyDocumentResponse | InvokeFunctionParams | GetDownloadUrlsParams | DeleteFilesParams
action: string
}
export default function cloudApiRequest(args: cloudApiRequestArgs): Promise<CloudApiResponse> {
const { config, params, action } = args
Iif (!actionName[action]) {
throw new Error(`invalid action: ${action}`)
}
// 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
let cred = new Credential(config.secretId, config.secretKey);
let httpProfile = new HttpProfile();
httpProfile.endpoint = "tcb.tencentcloudapi.com";
httpProfile.reqMethod = "POST"
let clientProfile = new ClientProfile();
clientProfile.httpProfile = httpProfile;
// 实例化要请求产品(以cvm为例)的client对象
let client = new Client(cred, "ap-shanghai", clientProfile);
return new Promise((resolve, reject) => {
// 实例化一个请求对象
let req = new Models[`${action}Request`]();
req.deserialize({
...params,
CommParam: {
EnvName: config.envName,
Module: actionMapping[action]
}
})
// 通过client对象调用想要访问的接口,需要传入请求对象以及响应回调函数
client[action](req, function (errMsg, response) {
// 请求异常返回,打印异常信息
Iif (errMsg) {
reject(errMsg);
return;
}
// 请求正常返回,打印response对象
resolve(response);
});
})
}
|