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:

  1. Access Token:

    • STORAGE_DROPBOX_ACCESS_TOKEN - A valid Dropbox API access token
  2. Refresh Token:

    • STORAGE_DROPBOX_REFRESH_TOKEN - A valid Dropbox API refresh token
    • STORAGE_DROPBOX_APP_KEY - Your Dropbox application key (client ID)
    • STORAGE_DROPBOX_APP_SECRET - Your Dropbox application secret

Optional configuration:

  • STORAGE_DROPBOX_ROOT_PATH - Path within Dropbox to use as the root (defaults to empty which is the root)

Example

// Set required environment variables
process.env.STORAGE_DROPBOX_ACCESS_TOKEN = 'your-access-token';

// Create the provider
const storage = new DropboxFileStorage();

// Upload a file
const fileContent = Buffer.from('Hello, Dropbox!');
await storage.PutObject('documents/hello.txt', fileContent, 'text/plain');

// Download a file
const downloadedContent = await storage.GetObject('documents/hello.txt');

// Get a temporary download URL
const downloadUrl = await storage.CreatePreAuthDownloadUrl('documents/hello.txt');

Hierarchy (view full)

Constructors

Properties

_accessToken: string

Access token for Dropbox authentication

_client: Dropbox

Dropbox API client instance

_rootPath: string

Root path within Dropbox to use as the storage root

providerName: "Dropbox" = 'Dropbox'

The name of this storage provider

Accessors

Methods

  • 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.

    Parameters

    • sourceObjectName: string

      Path to the source object (e.g., 'templates/report-template.docx')

    • destinationObjectName: string

      Path where the copy should be created (e.g., 'documents/new-report.docx')

    Returns Promise<boolean>

    A Promise that resolves to true if successful, false if an error occurs

    Remarks

    • Works with both files and folders
    • If the destination already exists, the operation will fail
    • Parent directories must exist in the destination path

    Example

    // 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.

    Parameters

    • directoryPath: string

      Path where the directory should be created (e.g., 'documents/reports/2023')

    Returns Promise<boolean>

    A Promise that resolves to true if successful, false if an error occurs

    Remarks

    • Returns true if the directory already exists (idempotent operation)
    • Trailing slashes in the path are automatically removed
    • Parent directories must already exist; this method doesn't create them recursively

    Example

    // 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.

    Parameters

    • objectName: string

      Path to the file to download (e.g., 'documents/report.pdf')

    Returns Promise<string>

    A Promise that resolves to the download URL string

    Throws

    Error if the file doesn't exist or URL creation fails

    Remarks

    • Dropbox temporary download links typically expire after 4 hours
    • Generated URLs can be shared with users who don't have Dropbox access

    Example

    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.

    Parameters

    • objectName: string

      The object name (path) to create a pre-auth URL for

    Returns Promise<CreatePreAuthUploadUrlPayload>

    Throws

    UnsupportedOperationError always, as this operation is not supported

    Example

    // 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.

    Parameters

    • directoryPath: string

      Path to the directory to delete (e.g., 'documents/old-reports')

    • recursive: boolean = true

      If true, delete the directory and all its contents; if false, only delete if empty

    Returns Promise<boolean>

    A Promise that resolves to true if successful, false if an error occurs

    Remarks

    • Returns true if the directory doesn't exist (idempotent operation)
    • If recursive=false and the directory contains files, the operation will fail
    • Dropbox puts deleted folders in the trash, where they can be recovered for a limited time
    • Trailing slashes in the path are automatically removed

    Example

    // 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.

    Parameters

    • objectName: string

      Path to the object to delete (e.g., 'documents/old-report.docx')

    Returns Promise<boolean>

    A Promise that resolves to true if successful, false if an error occurs

    Remarks

    • Returns true if the object doesn't exist (for idempotency)
    • Dropbox puts deleted items in the trash, where they can be recovered for a limited time
    • For deleting folders with contents, use DeleteDirectory with recursive=true

    Example

    // 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.

    Parameters

    • directoryPath: string

      Path to check (e.g., 'documents/reports')

    Returns Promise<boolean>

    A Promise that resolves to true if the directory exists, false otherwise

    Remarks

    • Returns false if the path exists but points to a file instead of a folder
    • Trailing slashes in the path are automatically removed

    Example

    // 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.

    Parameters

    • params: GetObjectParams

      Object identifier (prefer objectId for performance, fallback to fullPath)

    Returns Promise<Buffer>

    A Promise that resolves to a Buffer containing the file's contents

    Throws

    Error if the file doesn't exist or cannot be downloaded

    Remarks

    • This method will throw an error if the object is a folder
    • For large files, consider using CreatePreAuthDownloadUrl instead

    Example

    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.

    Parameters

    Returns Promise<StorageObjectMetadata>

    A Promise that resolves to a StorageObjectMetadata object

    Throws

    Error if the object doesn't exist or cannot be accessed

    Example

    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.

    Parameters

    • prefix: string

      Path to the directory to list (e.g., 'documents/reports')

    • delimiter: string = '/'

      Optional delimiter character (default: '/')

    Returns Promise<StorageListResult>

    A Promise that resolves to a StorageListResult containing objects and prefixes

    Remarks

    • The objects array includes both files and folders
    • The prefixes array includes only folder paths (with trailing slashes)
    • Returns empty arrays if the directory doesn't exist or an error occurs
    • The delimiter parameter is included for interface compatibility but not used internally

    Example

    // 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.

    Parameters

    • oldObjectName: string

      Current path of the object (e.g., 'old-folder/document.docx')

    • newObjectName: string

      New path for the object (e.g., 'new-folder/renamed-document.docx')

    Returns Promise<boolean>

    A Promise that resolves to true if successful, false otherwise

    Remarks

    • Works with both files and folders
    • For folders, all contents will move with the folder
    • If the destination already exists, the operation will fail

    Example

    // 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.

    Parameters

    • objectName: string

      Path to check (e.g., 'documents/report.pdf')

    Returns Promise<boolean>

    A Promise that resolves to true if the object exists, false otherwise

    Example

    // 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.

    Parameters

    • objectName: string

      Path where the file should be uploaded (e.g., 'documents/report.pdf')

    • data: Buffer

      Buffer containing the file content

    • Optional contentType: string

      Optional 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)

    Returns Promise<boolean>

    A Promise that resolves to true if successful, false if an error occurs

    Remarks

    • Files smaller than 150MB use a simple upload
    • Files 150MB or larger use a chunked upload process
    • If a file with the same name exists, it will be overwritten
    • Parent folders must exist before uploading files to them

    Example

    // 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.

    Parameters

    • query: string

      The search query string (supports natural language and quoted phrases)

    • Optional options: FileSearchOptions

      Search options for filtering and limiting results

    Returns Promise<FileSearchResultSet>

    A Promise resolving to search results

    Remarks

    • Content search (searchContent: true) searches both filename and file content
    • Filename search (searchContent: false, default) searches only filenames
    • File type filtering converts extensions to Dropbox file categories
    • Date filters use server_modified timestamp
    • Path prefix restricts search to a specific folder and its subfolders

    Example

    // 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

    Checks if a filename contains the search query. Performs case-insensitive matching.

    Parameters

    • filename: string

      The filename to check

    • query: string

      The search query

    Returns boolean

    True if the filename contains the query

  • Private

    Extracts file extensions from fileTypes array. Converts MIME types to extensions and removes duplicates.

    Parameters

    • fileTypes: string[]

      Array of file types (extensions or MIME types)

    Returns string[]

    Array of file extensions without leading dots

  • Private

    Extracts the relative path from a Dropbox absolute path. Removes the root path prefix if configured.

    Parameters

    • dropboxPath: string

      The absolute Dropbox path

    Returns string

    The relative path without root prefix

  • Private

    Gets metadata for a file or folder from Dropbox

    This helper method retrieves metadata for a file or folder using the Dropbox API.

    Parameters

    • path: string

      The path to get metadata for

    Returns Promise<any>

    A Promise that resolves to the Dropbox metadata object

    Throws

    Error if the item doesn't exist or cannot be accessed

  • Private

    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.

    Parameters

    • path: string

      The path to normalize

    Returns string

    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.

    Returns Promise<void>

    A Promise that resolves when initialization is complete.

    Example

    // 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
  • Helper method to throw an UnsupportedOperationError with appropriate context. This method simplifies implementation of methods not supported by specific providers.

    Parameters

    • methodName: string

      The name of the method that is not supported

    Returns never

    Throws

    UnsupportedOperationError with information about the unsupported method and provider