-
Notifications
You must be signed in to change notification settings - Fork 55
/
files.ts
65 lines (54 loc) · 2.29 KB
/
files.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
import { AuthConfig } from 'flex-dev-utils/dist/credentials';
import FormData from 'form-data';
import { createReadStream } from 'fs';
import { basename } from 'path';
import { isSidOfType } from 'flex-dev-utils/dist/sids';
import BaseClient from './baseClient';
import Http from './http';
import { FileVisibility, Version, File } from './serverless-types';
import ServiceClient from './services';
type FileTypes = 'Functions' | 'Assets';
export default abstract class FilesClient extends BaseClient {
protected serviceSid: string;
private readonly fileType: FileTypes;
protected constructor(auth: AuthConfig, fileType: FileTypes, serviceSid: string) {
super(auth, `${ServiceClient.getBaseUrl()}/Services/${serviceSid}`);
if (!isSidOfType(serviceSid, 'ZS')) {
throw new Error(`ServiceSid ${serviceSid} is not valid`);
}
this.fileType = fileType;
this.serviceSid = serviceSid;
}
/**
* Uploads the provided filePath as a new {@link File}.
* This endpoint creates a new {@link File}, a new {@link Version} for it, and then uploads the file to S3
*
* @param friendlyName the friendlyName of the File
* @param uri the uri of the File
* @param localFilePath the local path to the file
* @param isProtected whether to upload this file as Public or Protected
*/
public upload = async (friendlyName: string, uri: string, localFilePath: string, isProtected: boolean = true) => {
const file = await this._create(friendlyName);
const contentConfig = {
filename: basename(localFilePath),
contentType: Http.getContentType(localFilePath),
};
const form = new FormData();
form.append('Path', uri);
form.append('Visibility', isProtected ? FileVisibility.Protected : FileVisibility.Public);
form.append('Content', createReadStream(localFilePath), contentConfig);
const baseUrl = ServiceClient.getBaseUrl('serverless-upload');
const url = `${baseUrl}/Services/${this.serviceSid}/${this.fileType}/${file.sid}/Versions`;
return this.http.upload(url, form);
}
/**
* Creates a new {@link File}
* @param friendlyName the friendly name of the file
* @private
*/
private _create = (friendlyName: string): Promise<File> => {
return this.http
.post<File>(this.fileType, {FriendlyName: friendlyName});
}
}