-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathazure-storage-blob.ts
181 lines (170 loc) · 5.44 KB
/
azure-storage-blob.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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { createError, defineDriver } from "./utils";
import {
BlobServiceClient,
ContainerClient,
StorageSharedKeyCredential,
} from "@azure/storage-blob";
import { DefaultAzureCredential } from "@azure/identity";
export interface AzureStorageBlobOptions {
/**
* The name of the Azure Storage account.
*/
accountName: string;
/**
* The name of the storage container. All entities will be stored in the same container.
* @default "unstorage"
*/
containerName?: string;
/**
* The account key. If provided, the SAS key will be ignored. Only available in Node.js runtime.
*/
accountKey?: string;
/**
* The SAS key. If provided, the account key will be ignored.
*/
sasKey?: string;
/**
* The connection string. If provided, the account key and SAS key will be ignored. Only available in Node.js runtime.
*/
connectionString?: string;
}
const DRIVER_NAME = "azure-storage-blob";
export default defineDriver((opts: AzureStorageBlobOptions) => {
let containerClient: ContainerClient;
const getContainerClient = () => {
if (containerClient) {
return containerClient;
}
if (!opts.accountName) {
throw createError(DRIVER_NAME, "accountName");
}
let serviceClient: BlobServiceClient;
if (opts.accountKey) {
// StorageSharedKeyCredential is only available in Node.js runtime, not in browsers
const credential = new StorageSharedKeyCredential(
opts.accountName,
opts.accountKey
);
serviceClient = new BlobServiceClient(
`https://${opts.accountName}.blob.core.windows.net`,
credential
);
} else if (opts.sasKey) {
serviceClient = new BlobServiceClient(
`https://${opts.accountName}.blob.core.windows.net${opts.sasKey}`
);
} else if (opts.connectionString) {
// fromConnectionString is only available in Node.js runtime, not in browsers
serviceClient = BlobServiceClient.fromConnectionString(
opts.connectionString
);
} else {
const credential = new DefaultAzureCredential();
serviceClient = new BlobServiceClient(
`https://${opts.accountName}.blob.core.windows.net`,
credential
);
}
containerClient = serviceClient.getContainerClient(
opts.containerName || "unstorage"
);
return containerClient;
};
return {
name: DRIVER_NAME,
options: opts,
getInstance: getContainerClient,
async hasItem(key) {
return await getContainerClient().getBlockBlobClient(key).exists();
},
async getItem(key) {
try {
const blob = await getContainerClient()
.getBlockBlobClient(key)
.download();
if (isBrowser) {
return blob.blobBody ? await blobToString(await blob.blobBody) : null;
}
return blob.readableStreamBody
? (await streamToBuffer(blob.readableStreamBody)).toString()
: null;
} catch {
return null;
}
},
async setItem(key, value) {
await getContainerClient()
.getBlockBlobClient(key)
.upload(value, Buffer.byteLength(value));
},
async removeItem(key) {
await getContainerClient().getBlockBlobClient(key).delete();
},
async getKeys() {
const iterator = getContainerClient()
.listBlobsFlat()
.byPage({ maxPageSize: 1000 });
const keys: string[] = [];
for await (const page of iterator) {
const pageKeys = page.segment.blobItems.map((blob) => blob.name);
keys.push(...pageKeys);
}
return keys;
},
async getMeta(key) {
const blobProperties = await getContainerClient()
.getBlockBlobClient(key)
.getProperties();
return {
mtime: blobProperties.lastModified,
atime: blobProperties.lastAccessed,
cr: blobProperties.createdOn,
...blobProperties.metadata,
};
},
async clear() {
const iterator = getContainerClient()
.listBlobsFlat()
.byPage({ maxPageSize: 1000 });
for await (const page of iterator) {
await Promise.all(
page.segment.blobItems.map(
async (blob) =>
await getContainerClient().deleteBlob(blob.name, {
deleteSnapshots: "include",
})
)
);
}
},
};
});
const isBrowser = typeof window !== "undefined";
// Helper function to read a Node.js readable stream into a Buffer. (https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-blob)
async function streamToBuffer(
readableStream: NodeJS.ReadableStream
): Promise<Buffer> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
readableStream.on("data", (data: Buffer | string) => {
chunks.push(data instanceof Buffer ? data : Buffer.from(data));
});
readableStream.on("end", () => {
resolve(Buffer.concat(chunks));
});
readableStream.on("error", reject);
});
}
// Helper function used to convert a browser Blob into string. (https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-blob)
async function blobToString(blob: Blob) {
const fileReader = new FileReader();
return new Promise((resolve, reject) => {
fileReader.onloadend = (ev) => {
resolve(ev.target?.result);
};
// eslint-disable-next-line unicorn/prefer-add-event-listener
fileReader.onerror = reject;
// eslint-disable-next-line unicorn/prefer-blob-reading-methods
fileReader.readAsText(blob);
});
}