Google Drive implementation of the FileStorageBase interface.

This class provides methods for interacting with Google Drive as a file storage provider. It implements most of the abstract methods defined in FileStorageBase and handles Google Drive-specific authentication, authorization, and file operations.

Unlike other storage providers like S3 or Azure, Google Drive has native concepts of folders and files with hierarchical paths, which makes some operations more natural while others (like pre-authenticated upload URLs) are not directly supported.

It requires one of the following environment variables to be set:

  • STORAGE_GDRIVE_KEY_FILE: Path to a service account key file with Drive permissions
  • STORAGE_GDRIVE_CREDENTIALS_JSON: A JSON object containing service account credentials

Optionally, you can set:

  • STORAGE_GDRIVE_ROOT_FOLDER_ID: ID of a folder to use as the root (for isolation)

Example

// Create an instance of GoogleDriveFileStorage
const driveStorage = new GoogleDriveFileStorage();

// Generate a pre-authenticated download URL
const downloadUrl = await driveStorage.CreatePreAuthDownloadUrl('documents/report.pdf');

// List files in a directory
const files = await driveStorage.ListObjects('documents/');

// Upload a file directly
const uploaded = await driveStorage.PutObject('documents/report.pdf', fileData);

Hierarchy (view full)

Constructors

Properties

_clientID?: string

OAuth2 credentials for configuration checking

_clientSecret?: string
_drive: Drive

The Google Drive API client

_refreshToken?: string
_rootFolderId?: string

Optional root folder ID to restrict operations to a specific folder

providerName: "Google Drive" = 'Google Drive'

The name of this storage provider, used in error messages

Accessors

Methods

  • Copies an object within Google Drive.

    This method creates a copy of a file at a new location without removing the original. It uses the Google Drive API's native file copying capabilities.

    Parameters

    • sourceObjectName: string

      The path to the file to copy

    • destinationObjectName: string

      The path where the copy should be created

    Returns Promise<boolean>

    A Promise resolving to a boolean indicating success

    Example

    // Create a backup copy of an important file
    const copied = await driveStorage.CopyObject(
    'documents/contract.pdf',
    'backups/contract_2024-05-16.pdf'
    );

    if (copied) {
    console.log('File copied successfully');
    } else {
    console.log('Failed to copy file');
    }
  • Creates a directory in Google Drive.

    This method creates a folder at the specified path, creating parent folders as needed if they don't exist. Google Drive natively supports folders as a special file type with the 'application/vnd.google-apps.folder' MIME type.

    Parameters

    • directoryPath: string

      The path of the directory to create

    Returns Promise<boolean>

    A Promise resolving to a boolean indicating success

    Example

    // Create a new directory structure
    const created = await driveStorage.CreateDirectory('documents/reports/annual/');

    if (created) {
    console.log('Directory created successfully');
    } else {
    console.log('Failed to create directory');
    }
  • Creates a pre-authenticated download URL for an object in Google Drive.

    This method creates a temporary, public sharing link for a file that allows anyone with the link to access the file for a limited time (10 minutes). It uses Google Drive's permissions system to create a temporary reader permission for 'anyone' with an expiration time.

    Parameters

    • objectName: string

      The path to the file to download

    Returns Promise<string>

    A Promise resolving to the download URL

    Throws

    Error if the file cannot be found or the URL creation fails

    Example

    // Generate a pre-authenticated download URL for a PDF file
    const downloadUrl = await driveStorage.CreatePreAuthDownloadUrl('documents/report.pdf');

    // The URL can be shared with users or used in applications for direct download
    console.log(downloadUrl);
  • Deletes a directory and optionally its contents from Google Drive.

    This method deletes a folder at the specified path. If recursive is false, it will fail if the folder has any contents. If recursive is true, it deletes the folder and all its contents.

    Parameters

    • directoryPath: string

      The path of the directory to delete

    • recursive: boolean = false

      If true, deletes all contents recursively (default: false)

    Returns Promise<boolean>

    A Promise resolving to a boolean indicating success

    Example

    // Delete an empty directory
    const deleted = await driveStorage.DeleteDirectory('documents/temp/');

    // Delete a directory and all its contents
    const recursivelyDeleted = await driveStorage.DeleteDirectory('documents/old_projects/', true);
  • Deletes an object from Google Drive.

    This method locates the specified file by path and deletes it from Google Drive. By default, this moves the file to the trash rather than permanently deleting it, unless your Drive settings are configured for immediate permanent deletion.

    Parameters

    • objectName: string

      The path to the file to delete

    Returns Promise<boolean>

    A Promise resolving to a boolean indicating success

    Example

    // Delete a temporary file
    const deleted = await driveStorage.DeleteObject('temp/report-draft.pdf');

    if (deleted) {
    console.log('File successfully deleted');
    } else {
    console.log('Failed to delete file');
    }
  • Checks if a directory exists in Google Drive.

    This method verifies the existence of a folder at the specified path. It also checks that the item is actually a folder (has the correct MIME type), not a file with the same name.

    Parameters

    • directoryPath: string

      The path of the directory to check

    Returns Promise<boolean>

    A Promise resolving to a boolean indicating if the directory exists

    Example

    // Check if a directory exists before trying to save files to it
    const exists = await driveStorage.DirectoryExists('documents/reports/');

    if (!exists) {
    console.log('Directory does not exist, creating it first');
    await driveStorage.CreateDirectory('documents/reports/');
    }

    // Now safe to use the directory
    await driveStorage.PutObject('documents/reports/new-report.pdf', fileData);
  • Downloads an object's content from Google Drive.

    This method retrieves the full content of a file and returns it as a Buffer for processing in memory.

    Parameters

    • params: GetObjectParams

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

    Returns Promise<Buffer>

    A Promise resolving to a Buffer containing the file's data

    Throws

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

    Example

    try {
    // Fast path: Use objectId (Google Drive file ID)
    const content = await driveStorage.GetObject({ objectId: '1a2b3c4d5e' });

    // Slow path: Use path
    const content2 = await driveStorage.GetObject({ fullPath: 'documents/config.json' });

    // Parse the JSON content
    const config = JSON.parse(content.toString('utf8'));
    console.log('Configuration loaded:', config);
    } catch (error) {
    console.error('Failed to download file:', error.message);
    }
  • Retrieves metadata for a specific object in Google Drive.

    This method fetches the file information without downloading its content, which is more efficient for checking file attributes like size, type, and last modified date.

    Parameters

    Returns Promise<StorageObjectMetadata>

    A Promise resolving to a StorageObjectMetadata object

    Throws

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

    Example

    try {
    // Fast path: Use objectId (Google Drive file ID)
    const metadata = await driveStorage.GetObjectMetadata({ objectId: '1a2b3c4d5e' });

    // Slow path: Use path
    const metadata2 = await driveStorage.GetObjectMetadata({ fullPath: 'documents/report.pdf' });

    console.log(`File: ${metadata.name}`);
    console.log(`Size: ${metadata.size} bytes`);
    console.log(`Last modified: ${metadata.lastModified}`);
    } catch (error) {
    console.error('File does not exist or cannot be accessed');
    }
  • Lists objects in a directory in Google Drive.

    This method retrieves all files and folders directly inside the specified folder path. It handles Google Drive's native folder structure and converts the Drive API responses to the standardized StorageListResult format.

    Parameters

    • prefix: string

      The path to the directory to list

    • delimiter: string = '/'

      Delimiter character (unused in Google Drive implementation)

    Returns Promise<StorageListResult>

    A Promise resolving to a StorageListResult containing objects and prefixes

    Example

    // List all files and directories in the documents folder
    const result = await driveStorage.ListObjects('documents/');

    // Process files
    for (const file of result.objects) {
    console.log(`File: ${file.name}, Size: ${file.size}, Type: ${file.contentType}`);
    }

    // Process subdirectories
    for (const dir of result.prefixes) {
    console.log(`Directory: ${dir}`);
    }
  • Moves an object from one location to another within Google Drive.

    This method first locates the file to be moved, then gets or creates the destination folder, and finally updates the file's name and parent folder. Google Drive has native support for moving files between folders.

    Parameters

    • oldObjectName: string

      The current path of the object

    • newObjectName: string

      The new path for the object

    Returns Promise<boolean>

    A Promise resolving to a boolean indicating success

    Example

    // Move a file from drafts to published folder
    const success = await driveStorage.MoveObject(
    'drafts/report.docx',
    'published/final-report.docx'
    );

    if (success) {
    console.log('File successfully moved');
    } else {
    console.log('Failed to move file');
    }
  • Checks if an object exists in Google Drive.

    This method verifies the existence of a file at the specified path without downloading its content.

    Parameters

    • objectName: string

      The path to the file to check

    Returns Promise<boolean>

    A Promise resolving to a boolean indicating if the file exists

    Example

    // Check if a file exists before attempting to use it
    const exists = await driveStorage.ObjectExists('documents/report.pdf');

    if (exists) {
    console.log('File exists, proceeding with download');
    const content = await driveStorage.GetObject('documents/report.pdf');
    // Process the content...
    } else {
    console.log('File does not exist');
    }
  • Uploads data to an object in Google Drive.

    This method directly uploads a Buffer of data to a file with the specified path. It will create any necessary parent folders if they don't exist, and will update the file if it already exists or create a new one if it doesn't.

    Parameters

    • objectName: string

      The path to the file to upload

    • data: Buffer

      The Buffer containing the data to upload

    • Optional contentType: string

      Optional MIME type for the file (inferred from name if not provided)

    • Optional metadata: Record<string, string>

      Optional key-value pairs of custom metadata (not supported in current implementation)

    Returns Promise<boolean>

    A Promise resolving to a boolean indicating success

    Example

    // Upload a text file
    const content = Buffer.from('Hello, World!', 'utf8');
    const uploaded = await driveStorage.PutObject(
    'documents/hello.txt',
    content,
    'text/plain'
    );

    if (uploaded) {
    console.log('File uploaded successfully');
    } else {
    console.log('Failed to upload file');
    }
  • Searches for files in Google Drive using the Drive API search capabilities.

    Google Drive search syntax supports:

    • Simple terms: "report" matches files containing "report"
    • Exact phrases: "quarterly report" matches that exact phrase
    • Boolean OR: "budget OR forecast"
    • Exclusion: "report -draft" excludes files with "draft"
    • Wildcards: Not supported in Drive API

    Content search is always enabled for supported file types (Docs, Sheets, PDFs, etc.) when searchContent option is true.

    Parameters

    • query: string

      Search query using Google Drive search syntax

    • Optional options: FileSearchOptions

      Search options

    Returns Promise<FileSearchResultSet>

    Promise resolving to search results

    Example

    // Simple name 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
    const contentResults = await storage.SearchFiles('machine learning', {
    searchContent: true,
    pathPrefix: 'documents/research/'
    });
  • Private

    Helper method to convert Google Drive file objects to StorageObjectMetadata.

    This method transforms the Google Drive API's file representation into the standardized StorageObjectMetadata format used by the FileStorageBase interface. It handles special properties like folder detection and paths.

    Parameters

    • file: Schema$File

      The Google Drive file object to convert

    • parentPath: string = ''

      The parent path to use for constructing the full path

    Returns StorageObjectMetadata

    A StorageObjectMetadata representation of the file

  • Private

    Finds a file or folder by path.

    This helper method navigates the Google Drive folder structure to find a file or folder at the specified path. It starts from the root (or the configured root folder) and traverses the path components one by one.

    Parameters

    • path: string

      The path to the file or folder to find

    Returns Promise<Schema$File>

    A Promise resolving to the Google Drive file object

    Throws

    Error if the path cannot be found

  • Private

    Finds a parent folder by path and creates it if it doesn't exist.

    This helper method is used to ensure a folder path exists before creating or moving files. It navigates through each path component, creating folders as needed if they don't exist yet.

    Parameters

    • path: string

      The path to the folder to find or create

    Returns Promise<string>

    A Promise resolving to the ID of the folder

  • 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