storage-bucket-js
v1.0.0
Published
A comprehensive JavaScript/TypeScript library for storage bucket operations with API key authentication. Supports upload, download, list, and delete operations with CORS handling.
Maintainers
Readme
Storage Bucket JS
A comprehensive JavaScript/TypeScript library for storage bucket operations with API key authentication. Supports upload, download, list, and delete operations with CORS handling for web applications.
Features
- 🚀 Easy to Use: Simple and intuitive API
- 📁 File Operations: Upload, download, list, and delete files
- 🔐 Secure Authentication: API key-based authentication
- 📊 Progress Tracking: Upload and download progress callbacks
- 🌐 CORS Support: Built-in CORS handling for web applications
- 📱 Cross-Platform: Works in Node.js and browsers
- 📋 Pagination: Built-in pagination for file listings
- 🔍 Search & Filter: Search files and filter by MIME type
- 💪 TypeScript: Full TypeScript support with type definitions
- ⚡ Modern: Built with modern JavaScript/TypeScript
Installation
npm install storage-bucket-jsQuick Start
import { StorageBucketClient, ApiCredentials } from 'storage-bucket-js';
// Create credentials
const credentials = new ApiCredentials(
'sk_your_api_key_here',
'your_api_secret_here',
'https://your-storage-bucket-domain.com'
);
// Create client
const client = new StorageBucketClient(credentials);
// Test connection
try {
await client.testConnection();
console.log('Connected to storage bucket!');
} catch (error) {
console.error('Connection failed:', error.message);
}Usage Examples
File Upload
// Upload from File object (browser)
const fileInput = document.getElementById('file-input') as HTMLInputElement;
const file = fileInput.files[0];
try {
const result = await client.uploadFile(1, file, (loaded, total) => {
const progress = (loaded / total) * 100;
console.log(`Upload progress: ${progress.toFixed(2)}%`);
});
console.log('Upload successful:', result.file);
} catch (error) {
console.error('Upload failed:', error.message);
}
// Upload from buffer
const buffer = new Uint8Array([/* your file data */]);
const result = await client.uploadFileFromBuffer(
1,
'document.pdf',
buffer,
'application/pdf'
);File Download
// Download file as ArrayBuffer
const fileId = 123;
const buffer = await client.downloadFile(fileId, (loaded, total) => {
console.log(`Download progress: ${(loaded / total) * 100}%`);
});
// Download and save to device (browser)
await client.downloadFileToDevice(fileId, 'my-file.pdf');List Files
// List files with pagination
const response = await client.listFiles(1, {
page: 1,
limit: 20,
search: 'document',
mimeType: 'application/pdf',
sortBy: 'date',
sortOrder: 'desc'
});
console.log('Files:', response.files);
console.log('Pagination:', response.pagination);
// Iterate through all files
for (const file of response.files) {
console.log(`${file.fileName} (${file.fileSizeFormatted})`);
console.log(`Type: ${file.fileType}, Uploaded: ${file.uploadDate}`);
}File Management
// Get file information
const fileInfo = await client.getFileInfo(123);
console.log('File details:', fileInfo);
// Delete file
const deleteResult = await client.deleteFile(123);
if (deleteResult.success) {
console.log('File deleted successfully');
}Error Handling
import { StorageBucketException } from 'storage-bucket-js';
try {
await client.uploadFile(1, file);
} catch (error) {
if (error instanceof StorageBucketException) {
switch (error.statusCode) {
case 401:
console.error('Invalid API credentials');
break;
case 403:
console.error('Access denied');
break;
case 404:
console.error('File not found');
break;
case 429:
console.error('Rate limit exceeded');
break;
default:
console.error('Storage error:', error.message);
}
} else {
console.error('Unexpected error:', error);
}
}API Reference
StorageBucketClient
The main client class for interacting with the storage bucket API.
Constructor
new StorageBucketClient(credentials: ApiCredentials)Methods
testConnection(): Promise<boolean>- Test connection to the API serveruploadFile(bucketId: number, file: File, onProgress?: ProgressCallback): Promise<UploadResponse>- Upload a fileuploadFileFromBuffer(bucketId: number, fileName: string, buffer: ArrayBuffer | Uint8Array, mimeType?: string, onProgress?: ProgressCallback): Promise<UploadResponse>- Upload from bufferdownloadFile(fileId: number, onProgress?: ProgressCallback): Promise<ArrayBuffer>- Download file as bufferdownloadFileToDevice(fileId: number, fileName?: string, onProgress?: ProgressCallback): Promise<void>- Download and save to devicelistFiles(bucketId: number, options?: ListFilesOptions): Promise<FilesListResponse>- List files with filteringdeleteFile(fileId: number): Promise<DeleteResponse>- Delete a filegetFileInfo(fileId: number): Promise<BucketFile>- Get file information
ApiCredentials
new ApiCredentials(apiKey: string, apiSecret: string, baseUrl: string)apiKey- Your API key (must start with 'sk_')apiSecret- Your API secretbaseUrl- The base URL of your storage bucket API
BucketFile
Represents a file in the storage bucket with metadata and utility methods.
Properties:
id: number- File IDfileName: string- File namefileSize: number- File size in bytesfileSizeFormatted: string- Human-readable file sizemimeType: string- MIME typeuploadDate: Date- Upload timestampdownloadUrl: string- Download URLfileExtension: string- File extensionfileType: string- File type category (image, video, audio, document, other)isImage: boolean- True if file is an imageisVideo: boolean- True if file is a videoisAudio: boolean- True if file is an audio fileisDocument: boolean- True if file is a document
FileUtils
Utility class for file operations:
getFileName(filePath: string): string- Extract filename from pathgetFileExtension(fileName: string): string- Get file extensiongetMimeType(fileName: string): string | null- Get MIME type from filenamesanitizeFileName(fileName: string): string- Remove invalid characters from filenameformatFileSize(bytes: number): string- Format file size in human-readable formatisImage(mimeType: string): boolean- Check if MIME type is an imageisVideo(mimeType: string): boolean- Check if MIME type is a videoisAudio(mimeType: string): boolean- Check if MIME type is an audio fileisDocument(mimeType: string): boolean- Check if MIME type is a documentfileToArrayBuffer(file: File): Promise<ArrayBuffer>- Convert File to ArrayBufferdownloadBlob(blob: Blob, fileName: string): void- Trigger browser download
CORS Configuration
For web applications, you need to configure CORS on your storage bucket server. See the CORS Setup Guide for detailed instructions.
Environment Support
- Node.js: 16.0.0 or higher
- Browsers: Modern browsers with ES2020 support
- TypeScript: 4.0 or higher
License
MIT License - see LICENSE file for details.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Support
- Create an issue on GitHub
- Check the documentation
Changelog
See CHANGELOG.md for version history and changes.
