-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode-upload.ts
73 lines (63 loc) · 1.92 KB
/
node-upload.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
70
71
72
73
import type { Readable } from "node:stream";
import { CodexError } from "../errors/errors";
import type { SafeValue } from "../values/values";
import Undici from "undici";
import { type FormData } from "undici";
import type { UploadStategy, UploadStategyOptions } from "./types";
import { FetchAuthBuilder } from "../fetch-safe/fetch-safe";
export class NodeUploadStategy implements UploadStategy {
private readonly body:
| string
| Buffer
| Uint8Array
| null
| Readable
| FormData;
private readonly metadata:
| { filename?: string; mimetype?: string }
| undefined;
private abortController: AbortController | undefined;
constructor(
body: string | Buffer | Uint8Array | null | Readable | FormData,
metadata?: { filename?: string; mimetype?: string }
) {
this.body = body;
this.metadata = metadata;
}
async upload(
url: string,
{ auth }: UploadStategyOptions
): Promise<SafeValue<string>> {
const headers: Record<string, string> = FetchAuthBuilder.build(auth);
if (this.metadata?.filename) {
headers["Content-Disposition"] =
'attachment; filename="' + this.metadata?.filename + '"';
}
if (this.metadata?.mimetype) {
headers["Content-Type"] = this.metadata?.mimetype;
}
const controller = new AbortController();
this.abortController = controller;
const res = await Undici.request(url, {
method: "POST",
headers,
body: this.body,
signal: controller.signal,
});
if (res.statusCode < 200 || res.statusCode >= 300) {
const msg = `The status code is invalid got ${res.statusCode} - ${await res.body.text()} `;
return {
error: true,
data: new CodexError(msg, { code: res.statusCode }),
};
}
return { error: false, data: await res.body.text() };
}
abort(): void {
try {
this.abortController?.abort();
} catch (_) {
// Nothing to do
}
}
}