Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 | 2x 2x 2x 2x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 22x 22x 22x 18x 3x 3x 3x 18x 18x 18x 4x 4x 26x 10x 10x 10x 1x 9x 1x 8x 10x 10x 10x 10x 2x 2x 8x 6x 6x 2x 2x 6x 6x 6x 6x 1x 1x 5x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 3x 3x 2x 2x 3x 3x 2x 1x 2x 1x 1x 71x 71x 71x 71x 5x 66x 1x 1x 1x 1x 6x 6x 20x 9x 9x 20x 10x 2x 2x 11x 8x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x | /**
* @module @onlineapps/conn-base-storage
* @description MinIO storage connector with automatic SHA256 fingerprinting for OA Drive.
* Provides immutable content storage with verification, caching, and presigned URLs.
*
* @see {@link https://github.com/onlineapps/oa-drive/tree/main/shared/connector/conn-base-storage|GitHub Repository}
* @author OA Drive Team
* @license MIT
* @since 1.0.0
*/
const { StorageCore } = require('@onlineapps/storage-core');
const winston = require('winston');
const SharedUrlAdapter = require('./sharedUrlAdapter');
const runtimeCfg = require('./config');
/**
* Storage connector for MinIO with automatic fingerprinting
*
* @class StorageConnector
*
* @example <caption>Basic Usage</caption>
* const storage = new StorageConnector({
* endPoint: 'minio.example.com',
* port: 9000,
* accessKey: 'minioadmin',
* secretKey: 'minioadmin'
* });
*
* await storage.initialize();
* const result = await storage.uploadWithFingerprint(
* 'documents',
* { type: 'invoice', amount: 1500 },
* 'invoices'
* );
*
* @example <caption>With Caching</caption>
* const storage = new StorageConnector({
* cacheEnabled: true,
* maxCacheSize: 200
* });
*/
class StorageConnector {
/**
* Creates a new StorageConnector instance
*
* @constructor
* @param {Object} [config={}] - Configuration options
* @param {string} [config.endPoint='localhost'] - MinIO server endpoint
* @param {number} [config.port=9000] - MinIO server port
* @param {boolean} [config.useSSL=false] - Use SSL/TLS
* @param {string} [config.accessKey='minioadmin'] - Access key
* @param {string} [config.secretKey='minioadmin'] - Secret key
* @param {string} [config.defaultBucket='api-storage'] - Default bucket name
* @param {boolean} [config.cacheEnabled=true] - Enable content caching
* @param {number} [config.maxCacheSize=100] - Maximum cache entries
* @param {string} [config.logLevel='info'] - Logging level
*
* @example <caption>Full Configuration</caption>
* const storage = new StorageConnector({
* endPoint: 'minio.example.com',
* port: 9000,
* useSSL: true,
* accessKey: 'AKIAIOSFODNN7EXAMPLE',
* secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
* defaultBucket: 'production-storage',
* cacheEnabled: true,
* maxCacheSize: 500
* });
*/
constructor(config = {}) {
// Resolve runtime configuration for wrapper behavior
const resolved = runtimeCfg.resolve(config);
// Logger setup
this.logger = winston.createLogger({
level: resolved.logLevel,
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console()
]
});
// Create StorageCore instance (handles MinIO client internally)
this.core = new StorageCore({
endPoint: resolved.endPoint,
port: resolved.port,
useSSL: resolved.useSSL,
accessKey: resolved.accessKey,
secretKey: resolved.secretKey
});
// Expose MinIO client for backward compatibility
this.client = this.core.client;
this.minioClient = this.core.client;
this.defaultBucket = resolved.defaultBucket;
// Store config for access in tests
this.config = {
endPoint: this.core.config.endPoint,
port: this.core.config.port,
useSSL: this.core.config.useSSL,
accessKey: this.core.config.accessKey,
secretKey: this.core.config.secretKey,
bucketName: this.validateBucketName(config.bucketName || resolved.bucketName),
cacheMaxSize: resolved.cacheMaxSize
};
// Cache configuration
this.cacheEnabled = config.cacheEnabled !== false;
this.cache = new Map();
this.contentCache = new Map();
this.maxCacheSize = resolved.maxCacheSize;
// Track initialization
this.initialized = false;
// Initialize shared URL adapter
this.sharedUrl = new SharedUrlAdapter(this);
this.logger.info('StorageConnector initialized', {
endpoint: this.core.config.endPoint,
port: this.core.config.port,
defaultBucket: this.defaultBucket
});
}
/**
* Initialize connector and ensure bucket exists
*
* @async
* @method initialize
* @returns {Promise<boolean>} Returns true when initialized
*
* @throws {Error} If initialization fails
*
* @example
* try {
* await storage.initialize();
* console.log('Storage ready');
* } catch (error) {
* console.error('Failed to initialize:', error);
* }
*/
async initialize() {
try {
// Initialize StorageCore
await this.core.initialize();
// Ensure default bucket exists (using StorageCore)
const created = await this.core.ensureBucket(this.defaultBucket);
if (created) {
this.logger.info(`Bucket ${this.defaultBucket} created`);
// Set bucket policy for read access (business-specific feature)
const policy = {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: { AWS: ['*'] },
Action: ['s3:GetObject'],
Resource: [`arn:aws:s3:::${this.defaultBucket}/*`]
}
]
};
await this.client.setBucketPolicy(
this.defaultBucket,
JSON.stringify(policy)
);
}
this.logger.info('StorageConnector ready');
this.initialized = true;
return true;
} catch (error) {
this.logger.error('Failed to initialize StorageConnector', error);
throw error;
}
}
/**
* Generate SHA256 fingerprint for content
*
* @method generateFingerprint
* @param {string|Buffer|Object} content - Content to fingerprint
* @returns {string} SHA256 hash in hex format
*
* @example <caption>String Content</caption>
* const hash = storage.generateFingerprint('Hello World');
* // Returns: SHA256 hash
*
* @example <caption>Object Content</caption>
* const hash = storage.generateFingerprint({ name: 'John', age: 30 });
* // Returns consistent hash for the object
*/
generateFingerprint(content) {
// Delegate to StorageCore
return this.core.calculateFingerprint(content);
}
/**
* Upload content with automatic fingerprinting
*
* @async
* @method uploadWithFingerprint
* @param {string} bucket - Bucket name
* @param {string|Buffer|Object} content - Content to upload
* @param {string} [pathPrefix=''] - Path prefix for organization
* @returns {Promise<UploadResult>} Upload result with fingerprint
* @returns {string} result.fingerprint - SHA256 fingerprint
* @returns {string} result.bucket - Bucket name
* @returns {string} result.path - Storage path
* @returns {string} result.url - Public URL
* @returns {boolean} result.existed - Whether object already existed
*
* @throws {Error} If upload fails
*
* @example <caption>Upload JSON Object</caption>
* const result = await storage.uploadWithFingerprint(
* 'invoices',
* { invoiceId: 'INV-123', amount: 1500 },
* '2024/01'
* );
* console.log(`Stored at: ${result.url}`);
* console.log(`Fingerprint: ${result.fingerprint}`);
*
* @example <caption>Upload String Content</caption>
* const result = await storage.uploadWithFingerprint(
* 'documents',
* 'Important document content',
* 'contracts'
* );
*
* @example <caption>Upload Buffer</caption>
* const buffer = Buffer.from('Binary data');
* const result = await storage.uploadWithFingerprint(
* 'files',
* buffer
* );
*/
async uploadWithFingerprint(bucket, content, pathPrefix = '') {
try {
// Ensure bucket is provided
bucket = bucket || this.defaultBucket;
// Convert content to Buffer if needed
let buffer;
if (Buffer.isBuffer(content)) {
buffer = content;
} else if (typeof content === 'object') {
buffer = Buffer.from(JSON.stringify(content));
} else {
buffer = Buffer.from(content);
}
// Generate fingerprint
const fingerprint = this.generateFingerprint(buffer);
// Build path with fingerprint
const path = pathPrefix
? `${pathPrefix}/${fingerprint}.json`
: `${fingerprint}.json`;
// Check if object already exists (immutable) - using StorageCore
const exists = await this.core.objectExists(bucket, path);
if (exists) {
this.logger.debug(`Object already exists: ${bucket}/${path}`);
return {
fingerprint,
bucket,
path,
url: this.getPublicUrl(bucket, path),
existed: true
};
}
// Upload to MinIO - using StorageCore
await this.core.putObject(
bucket,
path,
buffer,
{
'Content-Type': 'application/json',
'x-amz-meta-fingerprint': fingerprint,
'x-amz-meta-uploaded-at': new Date().toISOString()
}
);
this.logger.info(`Uploaded content to ${bucket}/${path}`, { fingerprint });
return {
fingerprint,
bucket,
path,
url: this.getPublicUrl(bucket, path),
existed: false
};
} catch (error) {
this.logger.error('Upload failed', error);
throw error;
}
}
/**
* Download content and verify fingerprint
*
* @async
* @method downloadWithVerification
* @param {string} bucket - Bucket name
* @param {string} path - Object path
* @param {string} expectedFingerprint - Expected SHA256 fingerprint
* @returns {Promise<string>} Content as string
*
* @throws {Error} If download fails or fingerprint mismatch
*
* @example <caption>Download with Verification</caption>
* const content = await storage.downloadWithVerification(
* 'invoices',
* '2024/01/abc123.json',
* 'abc123...'
* );
* const data = JSON.parse(content);
*
* @example <caption>Handle Verification Failure</caption>
* try {
* const content = await storage.downloadWithVerification(
* 'documents',
* 'contract.json',
* expectedHash
* );
* } catch (error) {
* if (error.message.includes('Fingerprint mismatch')) {
* console.error('Content has been tampered!');
* }
* }
*/
async downloadWithVerification(bucket, path, expectedFingerprint) {
try {
bucket = bucket || this.defaultBucket;
// Check cache first
const cacheKey = `${bucket}/${path}/${expectedFingerprint}`;
if (this.cacheEnabled && this.contentCache.has(cacheKey)) {
this.logger.debug(`Cache hit for ${cacheKey}`);
return this.contentCache.get(cacheKey);
}
// Download from MinIO - using StorageCore
const stream = await this.core.getObject(bucket, path);
// Collect stream data
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
const buffer = Buffer.concat(chunks);
// Verify fingerprint if provided - using StorageCore
Eif (expectedFingerprint) {
const actualFingerprint = this.core.calculateFingerprint(buffer);
if (actualFingerprint !== expectedFingerprint) {
throw new Error(
`Fingerprint mismatch! Expected: ${expectedFingerprint}, Got: ${actualFingerprint}`
);
}
this.logger.debug(`Fingerprint verified for ${bucket}/${path}`);
}
// Convert to string
const content = buffer.toString('utf8');
// Update cache
Eif (this.cacheEnabled && expectedFingerprint) {
this.updateCache(cacheKey, content);
}
return content;
} catch (error) {
this.logger.error(`Download failed for ${bucket}/${path}`, error);
throw error;
}
}
/**
* Get pre-signed URL for direct access
*
* @async
* @method getPresignedUrl
* @param {string} bucket - Bucket name
* @param {string} path - Object path
* @param {number} [expiry=3600] - URL expiry in seconds
* @returns {Promise<string>} Pre-signed URL
*
* @throws {Error} If URL generation fails
*
* @example <caption>Generate Temporary URL</caption>
* const url = await storage.getPresignedUrl(
* 'invoices',
* '2024/01/invoice-123.json',
* 7200 // 2 hours
* );
* // Share URL with external service
*
* @example <caption>Short-lived URL</caption>
* const url = await storage.getPresignedUrl(
* 'temp',
* 'report.pdf',
* 300 // 5 minutes
* );
*/
async getPresignedUrl(bucket, path, expiry = 3600) {
try {
bucket = bucket || this.defaultBucket;
// Use StorageCore
const url = await this.core.getPresignedUrl(bucket, path, expiry);
this.logger.debug(`Generated presigned URL for ${bucket}/${path}`);
return url;
} catch (error) {
this.logger.error('Failed to generate presigned URL', error);
throw error;
}
}
/**
* List objects with fingerprint metadata
*
* @async
* @method listWithFingerprints
* @param {string} bucket - Bucket name
* @param {string} [prefix=''] - Path prefix to filter
* @returns {Promise<Array<ObjectInfo>>} List of objects with metadata
*
* @example <caption>List All Objects</caption>
* const objects = await storage.listWithFingerprints('invoices');
* objects.forEach(obj => {
* console.log(`${obj.name}: ${obj.fingerprint}`);
* });
*
* @example <caption>List with Prefix</caption>
* const objects = await storage.listWithFingerprints(
* 'documents',
* '2024/01/'
* );
*/
async listWithFingerprints(bucket, prefix = '') {
try {
bucket = bucket || this.defaultBucket;
// Use StorageCore to list objects
const objectNames = await this.core.listByPrefix(bucket, prefix, true);
// Get metadata for each object
const objects = [];
for (const name of objectNames) {
try {
const stat = await this.core.statObject(bucket, name);
objects.push({
name,
size: stat.size,
lastModified: stat.lastModified,
fingerprint: stat.metaData?.['x-amz-meta-fingerprint'],
uploadedAt: stat.metaData?.['x-amz-meta-uploaded-at']
});
} catch (err) {
// Skip objects that can't be stat'd
this.logger.warn(`Failed to stat object ${name}`, err);
}
}
return objects;
} catch (error) {
this.logger.error('Failed to list objects', error);
throw error;
}
}
/**
* Delete object (use with caution - breaks immutability)
*
* @async
* @method deleteObject
* @param {string} bucket - Bucket name
* @param {string} path - Object path
* @returns {Promise<boolean>} Returns true on successful deletion
*
* @throws {Error} If deletion fails
*
* @warning This breaks immutability - use only when necessary
*
* @example
* await storage.deleteObject('temp', 'temporary-file.json');
*/
async deleteObject(bucket, path) {
try {
bucket = bucket || this.defaultBucket;
// Use StorageCore
await this.core.deleteObject(bucket, path);
this.logger.warn(`Deleted object: ${bucket}/${path}`);
// Clear from cache
const cacheKeys = Array.from(this.contentCache.keys())
.filter(key => key.startsWith(`${bucket}/${path}/`));
cacheKeys.forEach(key => this.contentCache.delete(key));
return true;
} catch (error) {
this.logger.error(`Failed to delete ${bucket}/${path}`, error);
throw error;
}
}
/**
* Get public URL for an object
*
* @method getPublicUrl
* @param {string} bucket - Bucket name
* @param {string} path - Object path
* @returns {string} Public URL
*
* @example
* const url = storage.getPublicUrl('invoices', '2024/invoice-123.json');
* // Returns: http://localhost:9000/invoices/2024/invoice-123.json
*/
getPublicUrl(bucket, path) {
const protocol = this.client.useSSL ? 'https' : 'http';
const port = this.client.port === 80 || this.client.port === 443
? ''
: `:${this.client.port}`;
return `${protocol}://${this.client.host}${port}/${bucket}/${path}`;
}
/**
* Update cache with LRU eviction
*
* @private
* @method updateCache
* @param {string} key - Cache key
* @param {*} value - Value to cache
* @returns {void}
*/
updateCache(key, value) {
// Remove oldest entry if cache is full
Iif (this.contentCache.size >= this.maxCacheSize) {
const firstKey = this.contentCache.keys().next().value;
this.contentCache.delete(firstKey);
}
// Add new entry
this.contentCache.set(key, value);
}
/**
* Create bucket if not exists
*
* @async
* @method ensureBucket
* @param {string} bucketName - Bucket name to ensure
* @returns {Promise<boolean>} Returns true when bucket exists
*
* @throws {Error} If bucket creation fails
*
* @example
* await storage.ensureBucket('new-bucket');
*/
async ensureBucket(bucketName) {
try {
// Use StorageCore
const created = await this.core.ensureBucket(bucketName);
if (created) {
this.logger.info(`Bucket ${bucketName} created`);
}
return true;
} catch (error) {
this.logger.error(`Failed to ensure bucket ${bucketName}`, error);
throw error;
}
}
/**
* Validate bucket name according to S3 standards
*
* @method validateBucketName
* @param {string} name - Bucket name to validate
* @returns {string} Valid bucket name or default
*
* @example
* const validName = storage.validateBucketName('My-Bucket');
* // Returns: 'oa-drive-storage' (invalid characters)
*/
validateBucketName(name) {
// S3 bucket naming rules
const validName = /^[a-z0-9][a-z0-9\-\.]*[a-z0-9]$/;
const minLength = 3;
const maxLength = 63;
if (!name ||
name.length < minLength ||
name.length > maxLength ||
!validName.test(name)) {
return 'oa-drive-storage'; // Return default if invalid
}
return name;
}
/**
* Get object name with fingerprint appended
*
* @method getObjectNameWithFingerprint
* @param {string} originalName - Original file name
* @param {string} fingerprint - SHA256 fingerprint
* @returns {string} Name with fingerprint
*
* @example
* const name = storage.getObjectNameWithFingerprint('document.pdf', 'abc123...');
* // Returns: 'document-abc123...pdf'
*/
getObjectNameWithFingerprint(originalName, fingerprint) {
const parts = originalName.split('.');
const extension = parts.length > 1 ? '.' + parts.pop() : '';
const baseName = parts.join('.');
return `${baseName}-${fingerprint}${extension}`;
}
/**
* Extract fingerprint from object name
*
* @method extractFingerprintFromName
* @param {string} objectName - Object name with fingerprint
* @returns {string|null} Extracted fingerprint or null
*
* @example
* const fp = storage.extractFingerprintFromName('document-abc123def456.pdf');
* // Returns: 'abc123def456' if valid format
*/
extractFingerprintFromName(objectName) {
// Match pattern: name-<64-char-hex>.extension
const match = objectName.match(/-([a-f0-9]{64})(\.[^.]+)?$/);
return match ? match[1] : null;
}
/**
* Add item to cache with size limit
*
* @private
* @method addToCache
* @param {string} key - Cache key
* @param {*} value - Value to cache
* @returns {void}
*/
addToCache(key, value) {
// Remove oldest if at max size
if (this.cache.size >= this.config.cacheMaxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
/**
* Get item from cache
*
* @private
* @method getFromCache
* @param {string} key - Cache key
* @returns {*} Cached value or undefined
*/
getFromCache(key) {
return this.cache.get(key);
}
/**
* Clear all caches
*
* @method clearCache
* @returns {void}
*
* @example
* storage.clearCache();
* // All cached content cleared
*/
clearCache() {
this.cache.clear();
this.contentCache.clear();
}
/**
* Get internal URL for service-to-service communication
*
* @method getInternalUrl
* @param {string} bucket - Bucket name
* @param {string} path - Object path
* @returns {string} Internal URL with internal:// protocol
*
* @example
* const url = storage.getInternalUrl('invoices', 'invoice-123.json');
* // Returns: 'internal://storage/invoices/invoice-123.json'
*/
getInternalUrl(bucket, path) {
return `internal://storage/${bucket}/${path}`;
}
/**
* Get public URL for an object
*
* @deprecated Use getInternalUrl() for service-to-service communication
* @method getPublicUrl
* @param {string} bucket - Bucket name
* @param {string} path - Object path
* @returns {string} Internal URL for backward compatibility
*/
getPublicUrl(bucket, path) {
// Pro zpětnou kompatibilitu, vrací internal URL
return this.getInternalUrl(bucket, path);
}
/**
* Get presigned URL for temporary access
*
* @async
* @method getPresignedUrl
* @param {string} bucket - Bucket name
* @param {string} objectName - Object name
* @param {number} [expiry=86400] - URL expiry in seconds (default 24 hours)
* @returns {Promise<string>} Pre-signed URL
*
* @throws {Error} If URL generation fails
*
* @example
* const url = await storage.getPresignedUrl('documents', 'contract.pdf', 3600);
*/
async getPresignedUrl(bucket, objectName, expiry = 86400) {
try {
return await this.client.presignedUrl('GET', bucket, objectName, expiry);
} catch (error) {
this.logger.error('Failed to generate presigned URL', error);
throw error;
}
}
/**
* List objects with extracted fingerprints
*
* @async
* @method listObjectsWithFingerprints
* @param {string} bucket - Bucket name
* @param {string} [prefix=''] - Path prefix to filter
* @returns {Promise<Array<Object>>} List of objects with fingerprints
*
* @example
* const objects = await storage.listObjectsWithFingerprints('invoices', '2024/');
*/
async listObjectsWithFingerprints(bucket, prefix = '') {
try {
bucket = bucket || this.defaultBucket;
const objects = [];
return new Promise((resolve, reject) => {
const stream = this.client.listObjectsV2(bucket, prefix, true);
stream.on('data', obj => {
objects.push({
name: obj.name,
size: obj.size,
lastModified: obj.lastModified,
fingerprint: this.extractFingerprintFromName(obj.name)
});
});
stream.on('error', reject);
stream.on('end', () => resolve(objects));
});
} catch (error) {
this.logger.error('Failed to list objects', error);
throw error;
}
}
}
/**
* @typedef {Object} UploadResult
* @property {string} fingerprint - SHA256 fingerprint of content
* @property {string} bucket - Bucket name
* @property {string} path - Storage path
* @property {string} url - Public or internal URL
* @property {boolean} existed - Whether object already existed
*/
/**
* @typedef {Object} ObjectInfo
* @property {string} name - Object name
* @property {number} size - Object size in bytes
* @property {Date} lastModified - Last modification date
* @property {string} [fingerprint] - SHA256 fingerprint if available
* @property {string} [uploadedAt] - Upload timestamp
*/
// Export main class
module.exports = StorageConnector;
/**
* Factory function to create storage instance
*
* @function create
* @param {Object} config - Configuration object
* @returns {StorageConnector} New storage connector instance
*
* @example
* const storage = StorageConnector.create({
* endPoint: 'minio.example.com',
* accessKey: 'key',
* secretKey: 'secret'
* });
*/
module.exports.create = (config) => new StorageConnector(config);
/**
* Current version
* @constant {string}
*/
module.exports.VERSION = '1.0.0'; |