@qrvey/object-storage 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -3,9 +3,742 @@
3
3
  var storageBlob = require('@azure/storage-blob');
4
4
  var clientS3 = require('@aws-sdk/client-s3');
5
5
  var s3RequestPresigner = require('@aws-sdk/s3-request-presigner');
6
+ var stream = require('stream');
7
+ var libStorage = require('@aws-sdk/lib-storage');
6
8
 
7
- var C=(r,e)=>{if(e=Symbol[r])return e;throw Error("Symbol."+r+" is not defined")};var u=(r,e,t)=>(e=r[C("asyncIterator")])?e.call(r):(r=r[C("iterator")](),e={},t=(n,o)=>(o=r[n])&&(e[n]=s=>new Promise((a,i,c)=>(s=o.call(r,s),c=s.done,Promise.resolve(s.value).then(p=>a({value:p,done:c}),i)))),t("next"),t("return"),e);var l=class{constructor(e){this.containerName=e,this.blobServiceClient=storageBlob.BlobServiceClient.fromConnectionString(process.env.AZURE_STORAGE_CONNECTION_STRING);}async list(){let e=[],t=this.blobServiceClient.getContainerClient(this.containerName);try{for(var n=u(t.listBlobsFlat()),o,s,a;o=!(s=await n.next()).done;o=!1){let i=s.value;e.push(i.name);}}catch(s){a=[s];}finally{try{o&&(s=n.return)&&await s.call(n);}finally{if(a)throw a[0]}}return new Promise(i=>i({keys:e}))}getObject(e){return new Promise((t,n)=>{try{this.blobServiceClient.getContainerClient(this.containerName).getBlockBlobClient(e).download(0).then(a=>t({body:a.readableStreamBody,metadata:{},contentType:"",contentLength:0}));}catch(o){return n(o)}})}async getSignedUrl(e,t){return new Promise((n,o)=>{try{let a=this.blobServiceClient.getContainerClient(this.containerName).getBlockBlobClient(e),i=new Date,c=new Date(i);c.setMinutes(i.getMinutes()+t),a.generateSasUrl({permissions:storageBlob.BlobSASPermissions.parse("r"),startsOn:i,expiresOn:c}).then(p=>n(p));}catch(s){return o(s)}})}async upload(e,t,n){return new Promise((o,s)=>{try{this.blobServiceClient.getContainerClient(this.containerName).getBlockBlobClient(e).uploadStream(t).then(()=>o({key:e}));}catch(a){return s(a)}})}delete(e){return new Promise((t,n)=>{try{this.blobServiceClient.getContainerClient(this.containerName).getBlockBlobClient(e).delete().then(()=>t(!0));}catch(o){return n(o)}})}};var m=class{constructor(e){this.bucketName=e,this.s3Client=new clientS3.S3Client({});}async list(){let e=[],t;do{let n=new clientS3.ListObjectsV2Command({Bucket:this.bucketName,ContinuationToken:t}),o=await this.s3Client.send(n);if(o.Contents)for(let s of o.Contents)s.Key&&e.push(s.Key);t=o.NextContinuationToken;}while(t);return {keys:e}}async getObject(e){var o,s;let t=new clientS3.GetObjectCommand({Bucket:this.bucketName,Key:e}),n=await this.s3Client.send(t);return {body:n.Body,metadata:(o=n.Metadata)!=null?o:{},contentType:(s=n.ContentType)!=null?s:"",contentLength:n.ContentLength}}getSignedUrl(e,t=60){let n=t*60,o=new clientS3.GetObjectCommand({Bucket:this.bucketName,Key:e});return s3RequestPresigner.getSignedUrl(this.s3Client,o,{expiresIn:n})}async upload(e,t,n){let o=new clientS3.PutObjectCommand({Bucket:this.bucketName,Key:e,Body:t,Metadata:n});return await this.s3Client.send(o),{key:e}}async delete(e){let t=new clientS3.DeleteObjectCommand({Bucket:this.bucketName,Key:e});return await this.s3Client.send(t),!0}};var b=class{static async instance(e){var n;return ((n=process.env.OBJECT_STORAGE_SERVICE)==null?void 0:n.toLowerCase())==="azure_blob_storage"?new l(e):new m(e)}};var g=class r{constructor(e){r.bucketName=e;}static async getObjectStorageServiceInstance(e=r.bucketName){if(!e)throw new Error("Bucket name not provided or not valid value");return b.instance(e)}static async list(e){return r.getObjectStorageServiceInstance(e).then(t=>t.list())}static async getObject(e,t){return r.getObjectStorageServiceInstance(t).then(n=>n.getObject(e))}static async getSignedUrl(e,t,n){return r.getObjectStorageServiceInstance(n).then(o=>o.getSignedUrl(e,t))}static async upload(e,t,n,o){return r.getObjectStorageServiceInstance(o).then(s=>s.upload(e,t,n))}static async delete(e,t){return r.getObjectStorageServiceInstance(t).then(n=>n.delete(e))}};
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
10
 
9
- exports.ObjectStorageService = g;
11
+ var stream__default = /*#__PURE__*/_interopDefault(stream);
12
+
13
+ var __defProp = Object.defineProperty;
14
+ var __defProps = Object.defineProperties;
15
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
16
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
17
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
18
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
19
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
20
+ var __spreadValues = (a, b) => {
21
+ for (var prop in b || (b = {}))
22
+ if (__hasOwnProp.call(b, prop))
23
+ __defNormalProp(a, prop, b[prop]);
24
+ if (__getOwnPropSymbols)
25
+ for (var prop of __getOwnPropSymbols(b)) {
26
+ if (__propIsEnum.call(b, prop))
27
+ __defNormalProp(a, prop, b[prop]);
28
+ }
29
+ return a;
30
+ };
31
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
32
+
33
+ // src/shared/utils/errorHandler.ts
34
+ var errorMessages = {
35
+ AccessDenied: "Access denied",
36
+ AccountProblem: "There is a problem with your account",
37
+ AllAccessDisabled: "All access to this resource has been disabled",
38
+ BucketAlreadyExists: "The requested bucket name is not available",
39
+ BucketNotEmpty: "The bucket you tried to delete is not empty",
40
+ EntityTooLarge: "The entity you are trying to upload is too large",
41
+ ExpiredToken: "The provided token has expired",
42
+ InternalError: "An internal server error has occurred",
43
+ InvalidAccessKeyId: "The AWS access key ID you provided does not exist in our records",
44
+ InvalidBucketName: "The specified bucket name is not valid",
45
+ InvalidObjectState: "The operation is not valid for the current state of the object",
46
+ InvalidToken: "The provided token is invalid",
47
+ NoSuchBucket: "The specified bucket does not exist",
48
+ NoSuchKey: "The specified key does not exist",
49
+ PreconditionFailed: "The condition specified in the request is not met",
50
+ RequestTimeout: "The request timed out",
51
+ ServiceUnavailable: "The service is currently unavailable",
52
+ SignatureDoesNotMatch: "The request signature we calculated does not match the signature you provided",
53
+ SlowDown: "Please reduce your request rate",
54
+ TemporaryRedirect: "Temporary redirect",
55
+ DEFAULT: "An unknown error occurred"
56
+ };
57
+ var ErrorHandler = class {
58
+ static handleError(errorCode, errorMessage, errorObj) {
59
+ const errorResponse = {
60
+ code: errorCode,
61
+ message: errorMessage || errorMessages[errorCode] || errorMessages["DEFAULT"],
62
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
63
+ error: errorObj ? {
64
+ name: errorObj.name,
65
+ message: errorObj.message,
66
+ stack: errorObj.stack || null
67
+ } : null
68
+ };
69
+ return errorResponse;
70
+ }
71
+ };
72
+
73
+ // src/services/storage/blob/blobHelpers.ts
74
+ function BlobPropertiesResponseToObjectResponse(blobProperties) {
75
+ return {
76
+ lastModified: blobProperties.lastModified,
77
+ contentLength: blobProperties.contentLength,
78
+ contentType: blobProperties.contentType,
79
+ eTag: blobProperties.etag,
80
+ metadata: blobProperties.metadata,
81
+ contentEncoding: blobProperties.contentEncoding,
82
+ cacheControl: blobProperties.cacheControl,
83
+ contentDisposition: blobProperties.contentDisposition,
84
+ contentLanguage: blobProperties.contentLanguage
85
+ };
86
+ }
87
+
88
+ // src/services/storage/blob/blobStorage.service.ts
89
+ var BlobStorageService = class {
90
+ /**
91
+ * Retrieves the properties of a blob from the container by its name.
92
+ *
93
+ * @param {string} blobName - The name of the blob.
94
+ * @return {Promise<GetObjectResponse>} A promise that resolves to the blob properties.
95
+ */
96
+ constructor(containerName) {
97
+ this.containerName = containerName;
98
+ this.blobServiceClient = storageBlob.BlobServiceClient.fromConnectionString(
99
+ process.env.AZURE_STORAGE_CONNECTION_STRING
100
+ );
101
+ }
102
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
103
+ createUploadWriteStream(key) {
104
+ throw new Error("Method not implemented.");
105
+ }
106
+ getUploadUrl(key, expiresInMinutes) {
107
+ throw new Error("Method not implemented.");
108
+ }
109
+ /**
110
+ * Retrieves the properties of a blob from the container by its name.
111
+ *
112
+ * @param {string} blobName - The name of the blob.
113
+ * @return {Promise<GetObjectResponse>} A promise that resolves to the blob properties.
114
+ */
115
+ getHeadObject(blobName) {
116
+ return new Promise((resolve, reject) => {
117
+ try {
118
+ const containerClient = this.blobServiceClient.getContainerClient(
119
+ this.containerName
120
+ );
121
+ const blockBlobClient = containerClient.getBlockBlobClient(blobName);
122
+ blockBlobClient.getProperties().then((blobProperties) => {
123
+ return resolve(
124
+ BlobPropertiesResponseToObjectResponse(
125
+ blobProperties
126
+ )
127
+ );
128
+ }).catch(
129
+ (error) => reject(
130
+ ErrorHandler.handleError(
131
+ "DEFAULT",
132
+ "",
133
+ error
134
+ )
135
+ )
136
+ );
137
+ } catch (error) {
138
+ return reject(
139
+ ErrorHandler.handleError("DEFAULT", "", error)
140
+ );
141
+ }
142
+ });
143
+ }
144
+ /**
145
+ * Retrieves an object from the blob storage service.
146
+ *
147
+ * @param {string} blobName - The name of the blob to retrieve.
148
+ * @return {Promise<GetObjectResponse>} A promise that resolves to the object data, including the body, metadata, content type, and content length, or rejects with an error if there was an issue.
149
+ */
150
+ getObject(blobName) {
151
+ return new Promise((resolve, reject) => {
152
+ try {
153
+ const containerClient = this.blobServiceClient.getContainerClient(
154
+ this.containerName
155
+ );
156
+ const blockBlobClient = containerClient.getBlockBlobClient(blobName);
157
+ blockBlobClient.download(0).then((downloadBlockBlobResponse) => {
158
+ return resolve({
159
+ body: downloadBlockBlobResponse.readableStreamBody,
160
+ metadata: {},
161
+ contentType: "",
162
+ contentLength: 0
163
+ });
164
+ }).catch(
165
+ (error) => reject(
166
+ ErrorHandler.handleError(
167
+ "DEFAULT",
168
+ "",
169
+ error
170
+ )
171
+ )
172
+ );
173
+ } catch (error) {
174
+ return reject(
175
+ ErrorHandler.handleError("DEFAULT", "", error)
176
+ );
177
+ }
178
+ });
179
+ }
180
+ /**
181
+ * Retrieves a signed URL for the blob with the specified name that expires after a certain period.
182
+ *
183
+ * @param {string} blobName - The name of the blob to generate the signed URL for.
184
+ * @param {number} expiresInMinutes - The duration in minutes until the signed URL expires.
185
+ * @return {Promise<string>} A Promise that resolves with the signed URL.
186
+ */
187
+ getDownloadUrl(blobName, expiresInMinutes) {
188
+ return new Promise((resolve, reject) => {
189
+ try {
190
+ const containerClient = this.blobServiceClient.getContainerClient(
191
+ this.containerName
192
+ );
193
+ const blockBlobClient = containerClient.getBlockBlobClient(blobName);
194
+ const startDate = /* @__PURE__ */ new Date();
195
+ const expiryDate = new Date(startDate);
196
+ expiryDate.setMinutes(
197
+ startDate.getMinutes() + expiresInMinutes
198
+ );
199
+ blockBlobClient.generateSasUrl({
200
+ permissions: storageBlob.BlobSASPermissions.parse("r"),
201
+ startsOn: startDate,
202
+ expiresOn: expiryDate
203
+ }).then((sasUrl) => resolve(sasUrl)).catch(
204
+ (error) => reject(
205
+ ErrorHandler.handleError(
206
+ "DEFAULT",
207
+ "",
208
+ error
209
+ )
210
+ )
211
+ );
212
+ } catch (error) {
213
+ return reject(
214
+ ErrorHandler.handleError("DEFAULT", "", error)
215
+ );
216
+ }
217
+ });
218
+ }
219
+ /**
220
+ * Uploads a file to the blob storage service.
221
+ *
222
+ * @param {string} blobName - The name of the blob to upload.
223
+ * @param {FileContent} body - The content of the file to upload.
224
+ * @param {{ [key: string]: string } | undefined} [metadata] - Optional metadata to associate with the blob.
225
+ * @return {Promise<UploadResponse>} A promise that resolves to the response object containing the key of the uploaded blob, or rejects with an error if there was an issue.
226
+ */
227
+ upload(blobName, body, metadata) {
228
+ return new Promise((resolve, reject) => {
229
+ try {
230
+ const containerClient = this.blobServiceClient.getContainerClient(
231
+ this.containerName
232
+ );
233
+ const blockBlobClient = containerClient.getBlockBlobClient(blobName);
234
+ blockBlobClient.uploadStream(
235
+ body,
236
+ void 0,
237
+ void 0,
238
+ metadata
239
+ ).then(() => resolve({ key: blobName })).catch(
240
+ (error) => reject(
241
+ ErrorHandler.handleError(
242
+ "DEFAULT",
243
+ "",
244
+ error
245
+ )
246
+ )
247
+ );
248
+ } catch (error) {
249
+ return reject(
250
+ ErrorHandler.handleError("DEFAULT", "", error)
251
+ );
252
+ }
253
+ });
254
+ }
255
+ /**
256
+ * Deletes a blob from the blob storage service.
257
+ *
258
+ * @param {string} blobName - The name of the blob to be deleted.
259
+ * @return {Promise<boolean>} A promise that resolves to true if the blob is successfully deleted, or rejects with an error if there was an issue.
260
+ */
261
+ delete(blobName) {
262
+ return new Promise((resolve, reject) => {
263
+ try {
264
+ const containerClient = this.blobServiceClient.getContainerClient(
265
+ this.containerName
266
+ );
267
+ const blockBlobClient = containerClient.getBlockBlobClient(blobName);
268
+ blockBlobClient.delete().then(() => resolve(true)).catch(
269
+ (error) => reject(
270
+ ErrorHandler.handleError(
271
+ "DEFAULT",
272
+ "",
273
+ error
274
+ )
275
+ )
276
+ );
277
+ } catch (error) {
278
+ return reject(
279
+ ErrorHandler.handleError("DEFAULT", "", error)
280
+ );
281
+ }
282
+ });
283
+ }
284
+ /**
285
+ * Lists a chunk of blobs from the specified container client based on the provided options and continuation token.
286
+ *
287
+ * @param {ListRequestOptions} options - The options for listing the blobs.
288
+ * @param {string | undefined} continuationToken - The continuation token for pagination.
289
+ * @param {number} limit - The maximum number of blobs to list in a single page.
290
+ * @param {ContainerClient} containerClient - The container client to list the blobs from.
291
+ * @return {Promise<{ items: BlobItem[]; continuationToken?: string }>} - A promise that resolves to an object containing the list of blob items and an optional continuation token.
292
+ */
293
+ async listChunk(options, continuationToken, limit, containerClient) {
294
+ const iterator = containerClient.listBlobsFlat({
295
+ prefix: options.prefix
296
+ }).byPage({
297
+ maxPageSize: limit,
298
+ continuationToken
299
+ });
300
+ const items = [];
301
+ const response = (await iterator.next()).value;
302
+ items.push(...response.segment.blobItems);
303
+ return {
304
+ items,
305
+ continuationToken: response.continuationToken
306
+ };
307
+ }
308
+ /**
309
+ * Retrieves a list of blob contents based on the provided options.
310
+ *
311
+ * @param {ListRequestOptions} options - The options for listing the blob contents.
312
+ * @return {Promise<{ contents: BlobItem[]; nextContinuationToken?: string }>} A promise that resolves to the list of blob contents and the next continuation token.
313
+ */
314
+ async listContents(options) {
315
+ var _a;
316
+ let responseContents = [];
317
+ let continuationToken = options.pagination;
318
+ const limit = (_a = options.limit) != null ? _a : 1e3;
319
+ let continueListing = true;
320
+ const containerClient = this.blobServiceClient.getContainerClient(
321
+ this.containerName
322
+ );
323
+ while (continueListing) {
324
+ const response = await this.listChunk(
325
+ options,
326
+ continuationToken,
327
+ limit - responseContents.length,
328
+ containerClient
329
+ );
330
+ continuationToken = response.continuationToken;
331
+ responseContents = responseContents.concat(response.items);
332
+ if (responseContents.length >= limit || !continuationToken) {
333
+ continueListing = false;
334
+ }
335
+ }
336
+ return {
337
+ contents: responseContents,
338
+ nextContinuationToken: continuationToken
339
+ };
340
+ }
341
+ /**
342
+ * Lists blobs in the Azure Blob Storage container with pagination.
343
+ * @param options - The options for listing blobs.
344
+ * @returns A promise that resolves to a paginated list of blob names.
345
+ */
346
+ async list(options) {
347
+ var _a;
348
+ let items = [];
349
+ const response = await this.listContents(options);
350
+ items = response.contents.length ? response.contents.map((blob) => {
351
+ return {
352
+ key: blob.name,
353
+ lastModified: blob.properties.lastModified,
354
+ size: blob.properties.contentLength,
355
+ eTag: blob.properties.etag
356
+ };
357
+ }) : [];
358
+ return {
359
+ items,
360
+ pagination: ((_a = response.nextContinuationToken) == null ? void 0 : _a.length) ? response.nextContinuationToken : null,
361
+ count: items.length
362
+ };
363
+ }
364
+ /**
365
+ * Lists all blobs in the Azure Blob Storage container.
366
+ * @param options - The options for listing blobs.
367
+ * @returns A promise that resolves to list of blob names.
368
+ */
369
+ async listAll(options) {
370
+ var _a, _b;
371
+ let allItems = [];
372
+ let pagination = void 0;
373
+ do {
374
+ const response = await this.list(__spreadProps(__spreadValues({}, options), {
375
+ pagination
376
+ }));
377
+ if ((_a = response.items) == null ? void 0 : _a.length)
378
+ allItems = [...allItems, ...response.items];
379
+ pagination = (_b = response.pagination) != null ? _b : void 0;
380
+ } while (pagination);
381
+ return { items: allItems, count: allItems.length };
382
+ }
383
+ };
384
+
385
+ // src/services/storage/s3/s3Helpers.ts
386
+ function listResponseContentsToListResponseItems(responseContents) {
387
+ return responseContents.map((responseContent) => {
388
+ return {
389
+ key: responseContent.Key,
390
+ lastModified: new Date(responseContent.LastModified),
391
+ size: responseContent.Size,
392
+ eTag: responseContent.ETag
393
+ };
394
+ });
395
+ }
396
+ function s3ObjectToObjectResponse(s3Object) {
397
+ return {
398
+ body: s3Object.Body,
399
+ metadata: s3Object.Metadata,
400
+ contentType: s3Object.ContentType,
401
+ contentLength: s3Object.ContentLength,
402
+ contentEncoding: s3Object.ContentEncoding,
403
+ cacheControl: s3Object.CacheControl,
404
+ contentDisposition: s3Object.ContentDisposition,
405
+ contentLanguage: s3Object.ContentLanguage,
406
+ eTag: s3Object.ETag,
407
+ lastModified: s3Object.LastModified
408
+ };
409
+ }
410
+ var S3StorageService = class {
411
+ constructor(bucketName) {
412
+ this.s3Client = new clientS3.S3Client({
413
+ region: process.env.AWS_REGION
414
+ });
415
+ this.bucketName = bucketName;
416
+ }
417
+ /**
418
+ * Retrieves a chunk of objects from the S3 bucket based on the provided options.
419
+ *
420
+ * @param {ListRequestOptions} options - The options for listing the objects.
421
+ * @param {string | undefined} continuationToken - The continuation token for pagination.
422
+ * @param {number} limit - The maximum number of objects to retrieve.
423
+ * @return {Promise<ListObjectsV2CommandOutput>} - A promise that resolves to the response containing the list of objects and metadata.
424
+ */
425
+ async listChunk(options, continuationToken, limit) {
426
+ const command = new clientS3.ListObjectsV2Command({
427
+ Bucket: this.bucketName,
428
+ ContinuationToken: continuationToken || options.pagination,
429
+ Prefix: options.prefix,
430
+ MaxKeys: limit
431
+ });
432
+ return this.s3Client.send(command);
433
+ }
434
+ /**
435
+ * Retrieves a list of contents from the S3 bucket based on the provided options.
436
+ *
437
+ * @param {ListRequestOptions} options - The options for listing the contents.
438
+ * @return {Promise<{ contents: unknown[]; nextContinuationToken?: string }>} - A promise that resolves to an object containing the list of contents and an optional next continuation token.
439
+ */
440
+ async listContents(options) {
441
+ var _a, _b;
442
+ let responseContents = [];
443
+ let continuationToken = void 0;
444
+ const limit = (_a = options.limit) != null ? _a : 1e3;
445
+ let continueListing = true;
446
+ while (continueListing) {
447
+ const listChunkLimit = limit - responseContents.length;
448
+ const response = await this.listChunk(
449
+ options,
450
+ continuationToken,
451
+ listChunkLimit
452
+ );
453
+ continuationToken = response.NextContinuationToken;
454
+ responseContents = responseContents.concat((_b = response.Contents) != null ? _b : []);
455
+ if (responseContents.length >= limit || !continuationToken) {
456
+ continueListing = false;
457
+ }
458
+ }
459
+ return {
460
+ contents: responseContents,
461
+ nextContinuationToken: continuationToken
462
+ };
463
+ }
464
+ /**
465
+ * Lists objects in the S3 bucket with pagination.
466
+ * @param options - The options for listing objects.
467
+ * @returns A promise that resolves to a paginated list of object keys.
468
+ */
469
+ async list(options) {
470
+ var _a;
471
+ let items = [];
472
+ const response = await this.listContents(options);
473
+ items = response.contents.length ? listResponseContentsToListResponseItems(response.contents) : [];
474
+ return {
475
+ items,
476
+ pagination: (_a = response.nextContinuationToken) != null ? _a : null,
477
+ count: items.length
478
+ };
479
+ }
480
+ /**
481
+ * Lists all objects in the S3 bucket.
482
+ * @param options - The options for listing objects.
483
+ * @returns A promise that resolves to list of object keys.
484
+ */
485
+ async listAll(options) {
486
+ var _a;
487
+ let allItems = [];
488
+ let pagination = void 0;
489
+ do {
490
+ const response = await this.list(__spreadProps(__spreadValues({}, options), {
491
+ pagination
492
+ }));
493
+ if ((_a = response.items) == null ? void 0 : _a.length)
494
+ allItems = [...allItems, ...response.items];
495
+ pagination = response.pagination === null ? void 0 : response.pagination;
496
+ } while (pagination);
497
+ return { items: allItems, count: allItems.length };
498
+ }
499
+ /**
500
+ * Retrieves an object from the S3 bucket.
501
+ * @param key - The key of the object to retrieve.
502
+ * @returns A promise that resolves to the content of the file.
503
+ */
504
+ async getHeadObject(key) {
505
+ const command = new clientS3.HeadObjectCommand({
506
+ Bucket: this.bucketName,
507
+ Key: key
508
+ });
509
+ const response = await this.s3Client.send(command);
510
+ return s3ObjectToObjectResponse(response);
511
+ }
512
+ /**
513
+ * Retrieves an object from the S3 bucket.
514
+ * @param key - The key of the object to retrieve.
515
+ * @returns A promise that resolves to the content of the file.
516
+ */
517
+ async getObject(key) {
518
+ const command = new clientS3.GetObjectCommand({
519
+ Bucket: this.bucketName,
520
+ Key: key
521
+ });
522
+ const response = await this.s3Client.send(command);
523
+ return s3ObjectToObjectResponse(response);
524
+ }
525
+ /**
526
+ * Generates a signed URL for accessing an object in the S3 bucket.
527
+ * @param key - The key of the object.
528
+ * @param expiresInMinutes - The number of minutes the signed URL should be valid for. Defaults to 60 minutes.
529
+ * @returns A promise that resolves to the signed URL.
530
+ */
531
+ getDownloadUrl(key, expiresInMinutes = 60) {
532
+ const expiresIn = expiresInMinutes * 60;
533
+ const command = new clientS3.GetObjectCommand({
534
+ Bucket: this.bucketName,
535
+ Key: key
536
+ });
537
+ return s3RequestPresigner.getSignedUrl(this.s3Client, command, { expiresIn });
538
+ }
539
+ /**
540
+ * Retrieves a signed URL for uploading an object to the S3 bucket.
541
+ *
542
+ * @param {string} key - The key of the object to be uploaded.
543
+ * @param {number} [expiresInMinutes=60] - The number of minutes the signed URL should be valid for. Defaults to 60 minutes.
544
+ * @returns A promise that resolves to the signed URL.
545
+ */
546
+ async getUploadUrl(key, expiresInMinutes = 60) {
547
+ const expiresIn = expiresInMinutes * 60;
548
+ const putObjectCommandParams = {
549
+ Bucket: process.env.UPLOAD_BUCKET_NAME,
550
+ Key: key,
551
+ ACL: "private"
552
+ };
553
+ const command = new clientS3.PutObjectCommand(putObjectCommandParams);
554
+ const signedUrl = await s3RequestPresigner.getSignedUrl(this.s3Client, command, {
555
+ expiresIn
556
+ });
557
+ return {
558
+ signedUrl,
559
+ key: `https://${process.env.UPLOAD_BUCKET_NAME}.s3.${process.env.AWS_DEFAULT_REGION}.amazonaws.com/${key}`
560
+ };
561
+ }
562
+ /**
563
+ * Uploads an object to the S3 bucket.
564
+ * @param key - The key of the object to upload.
565
+ * @param body - The content of the object to upload.
566
+ * @param metadata - Optional metadata to associate with the object.
567
+ * @returns A promise that resolves to the response containing the key of the uploaded object.
568
+ */
569
+ async upload(key, body, metadata) {
570
+ const command = new clientS3.PutObjectCommand({
571
+ Bucket: this.bucketName,
572
+ Key: key,
573
+ Body: body,
574
+ Metadata: metadata
575
+ });
576
+ await this.s3Client.send(command);
577
+ return { key };
578
+ }
579
+ /**
580
+ * Creates a writable stream for uploading a file to the S3 bucket.
581
+ *
582
+ * @param {string} key - The key of the object to upload.
583
+ * @return {CreateUploadWriteStreamResponse} An object containing the key of the uploaded object, the writable stream, and a promise that resolves when the upload is complete.
584
+ */
585
+ createUploadWriteStream(key) {
586
+ const streamPassThrough = new stream__default.default.PassThrough();
587
+ const params = {
588
+ Bucket: this.bucketName,
589
+ Key: key,
590
+ Body: streamPassThrough
591
+ };
592
+ const upload = new libStorage.Upload({
593
+ client: this.s3Client,
594
+ params
595
+ });
596
+ return {
597
+ key,
598
+ stream: streamPassThrough,
599
+ promise: upload.done()
600
+ };
601
+ }
602
+ /**
603
+ * Deletes an object from the S3 bucket.
604
+ * @param key - The key of the object to delete.
605
+ * @returns A promise that resolves to true if the object was deleted successfully.
606
+ */
607
+ async delete(key) {
608
+ const command = new clientS3.DeleteObjectCommand({
609
+ Bucket: this.bucketName,
610
+ Key: key
611
+ });
612
+ await this.s3Client.send(command);
613
+ return true;
614
+ }
615
+ };
616
+
617
+ // src/services/objectStorageFactory.service.ts
618
+ var ObjectStorageFactory = class {
619
+ static async instance(bucketName) {
620
+ var _a;
621
+ const isBlobStorageService = ((_a = process.env.OBJECT_STORAGE_SERVICE) == null ? void 0 : _a.toLowerCase()) === "azure_blob_storage";
622
+ if (isBlobStorageService) {
623
+ return new BlobStorageService(bucketName);
624
+ } else {
625
+ return new S3StorageService(bucketName);
626
+ }
627
+ }
628
+ };
629
+
630
+ // src/services/objectStorage.service.ts
631
+ var ObjectStorageService = class _ObjectStorageService {
632
+ constructor(bucketName) {
633
+ _ObjectStorageService.bucketName = bucketName;
634
+ }
635
+ static async getObjectStorageServiceInstance(bucketName = _ObjectStorageService.bucketName) {
636
+ if (!bucketName)
637
+ throw new Error("Bucket name not provided or not valid value");
638
+ return ObjectStorageFactory.instance(bucketName);
639
+ }
640
+ /**
641
+ * Retrieves a list of objects from the object storage service.
642
+ *
643
+ * @param {ListRequestOptions} options - The options to apply to the list operation.
644
+ * @param {string} [bucketName] - The name of the bucket to list objects from. If not provided, the default bucket name will be used.
645
+ * @return {Promise<ListResponse>} A promise that resolves to the list of objects.
646
+ */
647
+ static async list(options, bucketName) {
648
+ return _ObjectStorageService.getObjectStorageServiceInstance(
649
+ bucketName
650
+ ).then((instance) => instance.list(options));
651
+ }
652
+ /**
653
+ * Retrieves a list of all objects from the object storage service.
654
+ *
655
+ * @param {ListRequestOptions} options - The options to apply to the list operation.
656
+ * @param {string} [bucketName] - The name of the bucket to list objects from. If not provided, the default bucket name will be used.
657
+ * @return {Promise<ListResponse>} A promise that resolves to the list of all objects.
658
+ */
659
+ static async listAll(options, bucketName) {
660
+ return _ObjectStorageService.getObjectStorageServiceInstance(
661
+ bucketName
662
+ ).then((instance) => instance.listAll(options));
663
+ }
664
+ /**
665
+ * Retrieves an object from the object storage service.
666
+ *
667
+ * @param {string} key - The key of the object to retrieve.
668
+ * @param {string} [bucketName] - The name of the bucket where the object is stored. If not provided, the default bucket name will be used.
669
+ * @return {Promise<GetObjectResponse>} A promise that resolves to the retrieved object.
670
+ */
671
+ static async getObject(key, bucketName) {
672
+ return _ObjectStorageService.getObjectStorageServiceInstance(
673
+ bucketName
674
+ ).then((instance) => instance.getObject(key));
675
+ }
676
+ /**
677
+ * Retrieves a signed URL for the specified object in the object storage service.
678
+ *
679
+ * @param {string} key - The key of the object for which to generate the signed URL.
680
+ * @param {number} expiresInMinutes - The number of minutes until the signed URL expires.
681
+ * @param {string} [bucketName] - The name of the bucket where the object is stored. If not provided, the default bucket name will be used.
682
+ * @return {Promise<string>} A promise that resolves to the generated signed URL.
683
+ */
684
+ static async getDownloadUrl(key, expiresInMinutes, bucketName) {
685
+ return _ObjectStorageService.getObjectStorageServiceInstance(
686
+ bucketName
687
+ ).then((instance) => instance.getDownloadUrl(key, expiresInMinutes));
688
+ }
689
+ /**
690
+ * Retrieves an upload URL for the specified object in the object storage service.
691
+ *
692
+ * @param {string} key - The key of the object for which to generate the upload URL.
693
+ * @param {number} expiresInMinutes - The number of minutes until the upload URL expires.
694
+ * @param {string} [bucketName] - The name of the bucket where the object will be stored. If not provided, the default bucket name will be used.
695
+ * @return {Promise<string>} A promise that resolves to the generated upload URL.
696
+ */
697
+ static async getUploadUrl(key, expiresInMinutes, bucketName) {
698
+ return _ObjectStorageService.getObjectStorageServiceInstance(
699
+ bucketName
700
+ ).then((instance) => instance.getUploadUrl(key, expiresInMinutes));
701
+ }
702
+ /**
703
+ * Uploads a file to the object storage service.
704
+ *
705
+ * @param {string} key - The key of the object to upload.
706
+ * @param {FileContent} body - The content of the file to upload.
707
+ * @param {Object} [metadata] - Optional metadata to associate with the object.
708
+ * @param {string} [bucketName] - The name of the bucket where the object will be stored. If not provided, the default bucket name will be used.
709
+ * @return {Promise<UploadResponse>} A promise that resolves to the response of the upload operation.
710
+ */
711
+ static async upload(key, body, metadata, bucketName) {
712
+ return _ObjectStorageService.getObjectStorageServiceInstance(
713
+ bucketName
714
+ ).then((instance) => instance.upload(key, body, metadata));
715
+ }
716
+ /**
717
+ * Creates an upload write stream for the specified key in the object storage service.
718
+ *
719
+ * @param {string} key - The key of the object to create the upload write stream for.
720
+ * @param {string} [bucketName] - The name of the bucket where the object will be stored. If not provided, the default bucket name will be used.
721
+ * @return {Promise<CreateUploadWriteStreamResponse>} A promise that resolves to the response of the upload operation.
722
+ */
723
+ static async createUploadWriteStream(key, bucketName) {
724
+ return _ObjectStorageService.getObjectStorageServiceInstance(
725
+ bucketName
726
+ ).then((instance) => instance.createUploadWriteStream(key));
727
+ }
728
+ /**
729
+ * Deletes an object from the object storage service.
730
+ *
731
+ * @param {string} key - The key of the object to delete.
732
+ * @param {string} [bucketName] - The name of the bucket where the object is stored. If not provided, the default bucket name will be used.
733
+ * @return {Promise<boolean>} A promise that resolves to true if the object was successfully deleted, or false otherwise.
734
+ */
735
+ static async delete(key, bucketName) {
736
+ return _ObjectStorageService.getObjectStorageServiceInstance(
737
+ bucketName
738
+ ).then((instance) => instance.delete(key));
739
+ }
740
+ };
741
+
742
+ exports.ObjectStorageService = ObjectStorageService;
10
743
  //# sourceMappingURL=out.js.map
11
744
  //# sourceMappingURL=index.js.map