Repository navigation
Expand file tree
/
Copy pathstorage.ts
More file actions
126 lines (110 loc) · 3.48 KB
/
Copy pathstorage.ts
File metadata and controls
126 lines (110 loc) · 3.48 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import { fetchWithTimeout } from "@dub/utils";
import { AwsClient } from "aws4fetch";
interface imageOptions {
contentType?: string;
width?: number;
height?: number;
}
class StorageClient {
private client: AwsClient;
constructor() {
this.client = new AwsClient({
accessKeyId: process.env.STORAGE_ACCESS_KEY_ID || "",
secretAccessKey: process.env.STORAGE_SECRET_ACCESS_KEY || "",
service: "s3",
region: "auto",
});
}
async upload(key: string, body: Blob | Buffer | string, opts?: imageOptions) {
let uploadBody;
if (typeof body === "string") {
if (this.isBase64(body)) {
uploadBody = this.base64ToArrayBuffer(body, opts);
} else if (this.isUrl(body)) {
uploadBody = await this.urlToBlob(body, opts);
} else {
throw new Error("Invalid input: Not a base64 string or a valid URL");
}
} else {
uploadBody = body;
}
const headers = {
"Content-Length": uploadBody.size.toString(),
};
if (opts?.contentType) headers["Content-Type"] = opts.contentType;
try {
await this.client.fetch(`${process.env.STORAGE_ENDPOINT}/${key}`, {
method: "PUT",
headers,
body: uploadBody,
});
return {
url: `${process.env.STORAGE_BASE_URL}/${key}`,
};
} catch (error) {
throw new Error(`Failed to upload file: ${error.message}`);
}
}
async delete(key: string) {
await this.client.fetch(`${process.env.STORAGE_ENDPOINT}/${key}`, {
method: "DELETE",
});
return { success: true };
}
private base64ToArrayBuffer(base64: string, opts?: imageOptions) {
const base64Data = base64.replace(/^data:.+;base64,/, "");
const paddedBase64Data = base64Data.padEnd(
base64Data.length + ((4 - (base64Data.length % 4)) % 4),
"=",
);
const binaryString = atob(paddedBase64Data);
const byteArray = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
byteArray[i] = binaryString.charCodeAt(i);
}
const blobProps = {};
if (opts?.contentType) blobProps["type"] = opts.contentType;
return new Blob([byteArray], blobProps);
}
private isBase64(str: string): boolean {
const regex = /^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+);base64,([^\s]*)$/;
return regex.test(str);
}
private isUrl(str: string): boolean {
try {
new URL(str);
return true;
} catch (_) {
return false;
}
}
private async urlToBlob(url: string, opts?: imageOptions): Promise<Blob> {
let response: Response;
if (opts?.height || opts?.width) {
try {
const proxyUrl = new URL("https://wsrv.nl");
proxyUrl.searchParams.set("url", url);
if (opts.width) proxyUrl.searchParams.set("w", opts.width.toString());
if (opts.height) proxyUrl.searchParams.set("h", opts.height.toString());
proxyUrl.searchParams.set("fit", "cover");
response = await fetchWithTimeout(proxyUrl.toString());
} catch (error) {
response = await fetch(url);
}
} else {
response = await fetch(url);
}
if (!response.ok) {
throw new Error(`Failed to fetch URL: ${response.statusText}`);
}
const blob = await response.blob();
if (opts?.contentType) {
return new Blob([blob], { type: opts.contentType });
}
return blob;
}
}
export const storage = new StorageClient();
export const isStored = (url: string) => {
return url.startsWith(process.env.STORAGE_BASE_URL || "");
};