-
Notifications
You must be signed in to change notification settings - Fork 180
/
fileClient.ts
69 lines (60 loc) · 1.94 KB
/
fileClient.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { Client } from './client';
import { AuthenticationType } from './enums';
import debug from 'debug';
import { VetchError, HTTPMethods, VetchOptions } from '@vonage/vetch';
import fetch from 'node-fetch';
import { createWriteStream } from 'fs';
import { pipeline } from 'stream/promises';
const log = debug('vonage:file-client');
/**
* A client for downloading files from Vonage.
*
* @extends Client
*/
export class FileClient extends Client {
protected authType = AuthenticationType.JWT;
protected saveFilePath: string = '';
/**
* Downloads a file from Vonage and saves it to a specified path.
*
* @param {string} file - The URL or ID of the file to be downloaded.
* @param {string} path - The path where the downloaded file should be saved.
*
* @throws {Error} Throws an error if the file could not be downloaded or saved.
*
* @return {Promise<void>} Resolves when the file is successfully downloaded and saved.
*/
async downloadFile(file: string, path: string): Promise<void> {
log(`Downloading file: ${file}`);
let fileId = file;
try {
const fileURL = new URL(file);
fileId = fileURL.pathname.split('/').pop() || '';
} catch (_) {
log(`Not a url`);
}
log(`File Id ${fileId}`);
const request = await this.addAuthenticationToRequest({
url: `${this.config.apiHost}/v1/files/${fileId}`,
method: HTTPMethods.GET,
} as VetchOptions);
log('File download request', request);
const response = await fetch(
request.url,
{
method: request.method,
headers: request.headers as Record<string, string>,
},
);
log('File download response', response);
if (!response.ok) {
throw new VetchError(
`Unexpected response when downloading file: ${response.statusText}`,
request,
);
}
log(`Saving to ${path}`);
await pipeline(response.body, createWriteStream(path));
log('File saved');
}
}