-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcode.ts
55 lines (48 loc) · 1.52 KB
/
code.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import fs from 'fs'
import path from 'path'
import unzipper from 'unzipper'
import { CloudApiService, fetchStream, delSync, checkFullAccess } from '../utils'
interface IFunctionCodeOptions {
envId: string
destPath: string
functionName: string
codeSecret?: string
unzip?: boolean
}
const scfService = CloudApiService.getInstance('scf')
// 下载函数代码
export async function downloadFunctionCode(options: IFunctionCodeOptions) {
const { destPath, envId, functionName, codeSecret, unzip = false } = options
// 检验路径是否存在
checkFullAccess(destPath, true)
// 获取下载链接
const { Url } = await scfService.request('GetFunctionAddress', {
FunctionName: functionName,
Namespace: envId,
CodeSecret: codeSecret
})
// 下载文件
const res = await fetchStream(Url)
const zipPath = path.join(destPath, `${functionName}.zip`)
const dest = fs.createWriteStream(zipPath)
res.body.pipe(dest)
return new Promise<void>(resolve => {
// 解压文件
dest.on('close', () => {
// 不解压 ZIP 文件
if (!unzip) {
resolve()
return
}
const unzipStream = unzipper.Extract({
path: destPath
})
fs.createReadStream(zipPath).pipe(unzipStream)
unzipStream.on('close', () => {
// 删除 ZIP 文件
delSync([zipPath])
resolve()
})
})
})
}