Creates a new DropboxFileStorage instance
This constructor initializes the Dropbox client using the provided credentials from environment variables.
Error if neither access token nor refresh token with app credentials are provided
Private _accessAccess token for Dropbox authentication
Private _clientDropbox API client instance
Private _rootRoot path within Dropbox to use as the storage root
Protected Readonly providerThe name of this storage provider
Checks if Dropbox provider is properly configured. Returns true if access token is present.
Copies a file or folder from one location to another
This method creates a copy of a file or folder at a new location. The original file or folder remains unchanged.
Path to the source object (e.g., 'templates/report-template.docx')
Path where the copy should be created (e.g., 'documents/new-report.docx')
A Promise that resolves to true if successful, false if an error occurs
// Copy a template file to a new location with a different name
const copyResult = await storage.CopyObject(
'templates/financial-report.xlsx',
'reports/2023/q1-financial-report.xlsx'
);
if (copyResult) {
console.log('File copied successfully');
} else {
console.error('Failed to copy file');
}
Creates a new directory (folder) in Dropbox
This method creates a folder at the specified path.
Path where the directory should be created (e.g., 'documents/reports/2023')
A Promise that resolves to true if successful, false if an error occurs
// Create a new folder
const createResult = await storage.CreateDirectory('documents/reports/2023');
if (createResult) {
console.log('Directory created successfully');
// Now we can put files in this directory
await storage.PutObject(
'documents/reports/2023/annual-summary.xlsx',
fileContent,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
);
} else {
console.error('Failed to create directory');
}
Creates a pre-authenticated download URL for a file
This method generates a time-limited URL that can be used to download a file without authentication.
Path to the file to download (e.g., 'documents/report.pdf')
A Promise that resolves to the download URL string
Error if the file doesn't exist or URL creation fails
try {
// Generate a pre-authenticated download URL
const downloadUrl = await storage.CreatePreAuthDownloadUrl('documents/financial-report.pdf');
console.log(`Download the file using this URL: ${downloadUrl}`);
// The URL can be shared or used in a browser to download the file
// without requiring Dropbox authentication
} catch (error) {
console.error('Error creating download URL:', error.message);
}
Creates a pre-authenticated upload URL (not supported in Dropbox)
This method is not supported for Dropbox storage as Dropbox doesn't provide a way to generate pre-authenticated upload URLs like object storage services. Instead, use the PutObject method for file uploads.
The object name (path) to create a pre-auth URL for
UnsupportedOperationError always, as this operation is not supported
// This will throw an UnsupportedOperationError
try {
await storage.CreatePreAuthUploadUrl('documents/report.docx');
} catch (error) {
if (error instanceof UnsupportedOperationError) {
console.log('Pre-authenticated upload URLs are not supported in Dropbox.');
// Use PutObject instead
await storage.PutObject('documents/report.docx', fileContent);
}
}
Deletes a directory from Dropbox
This method deletes a folder and optionally ensures it's empty first. Note that Dropbox API always deletes folders recursively, so we perform an additional check when recursive=false to protect against accidental deletion.
Path to the directory to delete (e.g., 'documents/old-reports')
If true, delete the directory and all its contents; if false, only delete if empty
A Promise that resolves to true if successful, false if an error occurs
// Attempt to delete an empty folder
const deleteResult = await storage.DeleteDirectory('temp/empty-folder', false);
// Delete a folder and all its contents
const recursiveDeleteResult = await storage.DeleteDirectory('archive/old-data', true);
if (recursiveDeleteResult) {
console.log('Folder and all its contents deleted successfully');
} else {
console.error('Failed to delete folder');
}
Deletes a file or folder from Dropbox
This method permanently deletes a file or folder from Dropbox storage.
Path to the object to delete (e.g., 'documents/old-report.docx')
A Promise that resolves to true if successful, false if an error occurs
// Delete a file
const deleteResult = await storage.DeleteObject('temp/draft-document.docx');
if (deleteResult) {
console.log('File deleted successfully or already didn\'t exist');
} else {
console.error('Failed to delete file');
}
Checks if a directory exists
This method verifies whether a folder exists at the specified path. Unlike ObjectExists, this method also checks that the item is a folder.
Path to check (e.g., 'documents/reports')
A Promise that resolves to true if the directory exists, false otherwise
// Check if a directory exists before creating a file in it
const dirExists = await storage.DirectoryExists('documents/reports');
if (!dirExists) {
// Create the directory first
await storage.CreateDirectory('documents/reports');
}
// Now we can safely put a file in this directory
await storage.PutObject('documents/reports/annual-summary.pdf', fileContent);
Downloads a file's contents
This method retrieves the raw content of a file as a Buffer.
Object identifier (prefer objectId for performance, fallback to fullPath)
A Promise that resolves to a Buffer containing the file's contents
Error if the file doesn't exist or cannot be downloaded
try {
// Fast path: Use objectId (Dropbox file ID)
const fileContent = await storage.GetObject({ objectId: 'id:a4ayc_80_OEAAAAAAAAAXw' });
// Slow path: Use path
const fileContent2 = await storage.GetObject({ fullPath: 'documents/notes.txt' });
// Convert Buffer to string for text files
const textContent = fileContent.toString('utf8');
console.log('File content:', textContent);
// For binary files, you can write the buffer to disk
// or process it as needed
} catch (error) {
console.error('Error downloading file:', error.message);
}
Gets metadata for a file or folder
This method retrieves metadata information about a file or folder, such as its name, size, content type, and last modified date.
Object identifier (prefer objectId for performance, fallback to fullPath)
A Promise that resolves to a StorageObjectMetadata object
Error if the object doesn't exist or cannot be accessed
try {
// Fast path: Use objectId (Dropbox file ID)
const metadata = await storage.GetObjectMetadata({ objectId: 'id:a4ayc_80_OEAAAAAAAAAXw' });
// Slow path: Use path
const metadata2 = await storage.GetObjectMetadata({ fullPath: 'presentations/quarterly-update.pptx' });
console.log(`Name: ${metadata.name}`);
console.log(`Path: ${metadata.path}`);
console.log(`Size: ${metadata.size} bytes`);
console.log(`Content Type: ${metadata.contentType}`);
console.log(`Last Modified: ${metadata.lastModified}`);
console.log(`Is Directory: ${metadata.isDirectory}`);
// Dropbox-specific metadata is available in customMetadata
console.log(`Dropbox ID: ${metadata.customMetadata.id}`);
console.log(`Revision: ${metadata.customMetadata.rev}`);
} catch (error) {
console.error('Error getting metadata:', error.message);
}
Lists files and folders in a given directory
This method retrieves all files and subfolders in the specified directory. It returns both a list of object metadata and a list of directory prefixes.
Path to the directory to list (e.g., 'documents/reports')
Optional delimiter character (default: '/')
A Promise that resolves to a StorageListResult containing objects and prefixes
objects array includes both files and foldersprefixes array includes only folder paths (with trailing slashes)// List all files and folders in the 'documents' directory
const result = await storage.ListObjects('documents');
// Process files and folders
console.log(`Found ${result.objects.length} items:`);
for (const obj of result.objects) {
console.log(`- ${obj.name} (${obj.isDirectory ? 'Folder' : 'File'}, ${obj.size} bytes)`);
}
// List subfolders only
console.log(`Found ${result.prefixes.length} subfolders:`);
for (const prefix of result.prefixes) {
console.log(`- ${prefix}`);
}
Moves a file or folder from one location to another
This method moves a file or folder to a new location in Dropbox. It handles both renaming and changing the parent folder.
Current path of the object (e.g., 'old-folder/document.docx')
New path for the object (e.g., 'new-folder/renamed-document.docx')
A Promise that resolves to true if successful, false otherwise
// Move a file to a different folder and rename it
const moveResult = await storage.MoveObject(
'documents/old-report.pdf',
'archive/2023/annual-report.pdf'
);
if (moveResult) {
console.log('File moved successfully');
} else {
console.error('Failed to move file');
}
Checks if a file or folder exists
This method verifies whether an object (file or folder) exists at the specified path.
Path to check (e.g., 'documents/report.pdf')
A Promise that resolves to true if the object exists, false otherwise
// Check if a file exists before attempting to download it
const exists = await storage.ObjectExists('presentations/quarterly-update.pptx');
if (exists) {
// File exists, proceed with download
const fileContent = await storage.GetObject('presentations/quarterly-update.pptx');
// Process the file...
} else {
console.log('File does not exist');
}
Uploads a file to Dropbox
This method uploads a file to the specified path in Dropbox. It automatically determines whether to use a simple upload or chunked upload based on file size.
Path where the file should be uploaded (e.g., 'documents/report.pdf')
Buffer containing the file content
Optional contentType: stringOptional MIME type of the file (not used in Dropbox implementation)
Optional metadata: Record<string, string>Optional metadata to associate with the file (not used in Dropbox implementation)
A Promise that resolves to true if successful, false if an error occurs
// Upload a simple text file
const textContent = Buffer.from('This is a sample document', 'utf8');
const uploadResult = await storage.PutObject('documents/sample.txt', textContent);
// Upload a large file using chunked upload
const largeFileBuffer = fs.readFileSync('/path/to/large-presentation.pptx');
const largeUploadResult = await storage.PutObject(
'presentations/quarterly-results.pptx',
largeFileBuffer
);
if (largeUploadResult) {
console.log('Large file uploaded successfully');
} else {
console.error('Failed to upload large file');
}
Search files in Dropbox using Dropbox Search API v2.
Dropbox provides full-text search capabilities across file names and content. The search API supports natural language queries and can search both filenames and file content based on the searchContent option.
The search query string (supports natural language and quoted phrases)
Optional options: FileSearchOptionsSearch options for filtering and limiting results
A Promise resolving to search results
// Simple filename search
const results = await storage.SearchFiles('quarterly report');
// Search with file type filter
const pdfResults = await storage.SearchFiles('budget', {
fileTypes: ['pdf'],
modifiedAfter: new Date('2024-01-01')
});
// Content search within a specific folder
const contentResults = await storage.SearchFiles('machine learning', {
searchContent: true,
pathPrefix: 'documents/research',
maxResults: 50
});
Private _checkPrivate _convertPrivate Converts a Dropbox file/folder to StorageObjectMetadata
This helper method transforms Dropbox-specific metadata into the standard StorageObjectMetadata format used by FileStorageBase.
The Dropbox item metadata
Optional parent path string
A StorageObjectMetadata object
Private _extractPrivate _extractPrivate _getPrivate Gets metadata for a file or folder from Dropbox
This helper method retrieves metadata for a file or folder using the Dropbox API.
The path to get metadata for
A Promise that resolves to the Dropbox metadata object
Error if the item doesn't exist or cannot be accessed
Private _normalizePrivate Normalizes a path to be compatible with Dropbox API
This helper method ensures paths are formatted correctly for the Dropbox API, including proper handling of the root path prefix.
The path to normalize
A normalized path string suitable for Dropbox API calls
Optional initialization method for storage providers that require async setup.
This method can be overridden by subclasses that need to perform async initialization after construction, such as setting up access tokens, establishing connections, or verifying permissions.
The default implementation does nothing and resolves immediately. Storage provider implementations should override this method if they need to perform async setup.
A Promise that resolves when initialization is complete.
// In a specific provider implementation:
public async initialize(): Promise<void> {
// Set up OAuth tokens or other async initialization
await this.refreshAccessToken();
await this.verifyBucketAccess();
}
// Usage:
const storage = new MyStorageProvider();
await storage.initialize();
// Now the provider is ready to use
Protected throwHelper method to throw an UnsupportedOperationError with appropriate context. This method simplifies implementation of methods not supported by specific providers.
The name of the method that is not supported
UnsupportedOperationError with information about the unsupported method and provider
FileStorageBase implementation for Dropbox cloud storage
This provider allows working with files stored in Dropbox. It supports authentication via access token or refresh token with app credentials.
Remarks
This implementation requires one of the following authentication methods:
Access Token:
Refresh Token:
Optional configuration:
Example