-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfile-param.ts
More file actions
51 lines (46 loc) · 1.6 KB
/
Copy pathfile-param.ts
File metadata and controls
51 lines (46 loc) · 1.6 KB
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
import {IFileValue, IParam, IParamDto} from "./param.js";
import {IResultErrorDto} from "./result";
export interface UploadResponseDto {
FileId: string
FileName: string,
FileExt: string
}
export class FileValue {
constructor(
public readonly name: string,
public readonly fileId: string
) {}
}
export default class FileParam implements IParam {
/**
* Single file conversion parameter class.
*
* @param name - parameter name.
* @param file - value.
* @param host - ConvertApi server domain.
*/
constructor(
public readonly name: string,
public readonly file: File | FileValue | URL,
public readonly host: string
) {}
public value(): Promise<string> {
if (this.file instanceof FileValue) {
return Promise.resolve(this.file.fileId)
} else {
let uploadUrl = `https://${this.host}/upload?`
let response = this.file instanceof URL
? fetch(`${uploadUrl}url=${encodeURIComponent(this.file.href)}`, <RequestInit>{ method: 'POST' })
: fetch(`${uploadUrl}filename=${encodeURIComponent(this.file.name)}`, <RequestInit>{ method: 'POST', body: this.file })
return response
.then(r => r.ok ? r.json() : Promise.reject(<IResultErrorDto>{Code: 5007, Message: `Unable to upload the file`}))
.then(obj => obj.FileId)
}
}
public get dto(): Promise<IParamDto> {
return this.value().then( v => <IParamDto>{
Name: this.name,
FileValue: <IFileValue>{ Id: v }
})
}
}