import MPServerless from '@alicloud/mpserverless-node-sdk'; import getHttpClient from './utils/httpClient'; import { getServerSecret } from './utils/index'; interface InvokeRemoteFunctionOptions { /** * 小程序appId */ appId: string; /** * 空间id */ spaceId: string; /** * 函数名称 */ functionTarget: string; /** * 函数参数 */ functionArgs?: object; } function invokeFunction(functionService, functionTarget, functionArgs) { const encoder = functionService.getEncoder(); encoder.setBodyField({ method: 'serverless.function.runtime.invoke', params: { functionTarget, functionArgs, }, }); return functionService.transport.request(encoder); } /** * 调用云端函数 */ async function invokeRemoteFunction(options: InvokeRemoteFunctionOptions) { const { appId, spaceId, functionTarget, functionArgs = {} } = options; const serverSecret = await getServerSecret(appId, spaceId); const mpserverless = new MPServerless({ // 必填参数 spaceId, endpoint: 'https://api.bspapp.com', serverSecret, httpClient: getHttpClient(), logger: console, // 选填参数 //token: reqMeta.token, // userId: reqMeta.userId, //requestId: '12345678', }); const result = await invokeFunction(mpserverless.function, functionTarget, functionArgs); return result.body; } export default invokeRemoteFunction;