import fs from 'fs'; import path from 'path'; import { promisify } from 'util'; import { isEmpty, head } from 'lodash'; import request from '../../utils/request'; import download, { DownloadResult } from '../../utils/download'; import unzipCloudFunction from './unzip.function'; export interface DownloadCloudFunctionOptions { /** * 服务空间ID */ spaceId: string; /** * 云函数名 */ name: string; /** * 保存路径 */ path: string; /** * 小程序appId */ appId: string; /** * 下载后,是否自动解压 * @default false */ unzip: boolean; } interface Deployment { downloadSignedUrl: string; versionNo: string; createdAt: string; modifiedAt: string; deploymentId: string; } /** * 下载云函数 */ async function downloadCloudFunction( options: DownloadCloudFunctionOptions ): Promise { const { spaceId, name, path: downloadPath, appId, unzip = false } = options; // 1.查询云函数部署记录 const list = await request({ method: 'GET', host: 'ide', path: '/cli/cloud/function/deploymentList.json', needSign: true, data: { spaceId, name, pageNum: 1, pageSize: 1, status: '', appId, }, }); if (isEmpty(list)) { throw new Error(`云函数${name}没有部署记录`); } const dist = path.join(downloadPath, `${name}.zip`); // 2.下载最近部署记录 TS MODIFY const link = head(list)!.downloadSignedUrl; const donwloadResult = await download({ link, dist, }); if (unzip) { // 解压 await unzipCloudFunction(name, dist, downloadPath); // 删掉zip包 await promisify(fs.unlink)(dist); } return donwloadResult; } export default downloadCloudFunction;