Member Junction
    Preparing search index...

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

    Index

    Constructors

    Properties

    _accountId: string

    The ID of the FileStorageAccount this driver instance is operating for. Set during initialization via the config parameter.

    _accountName: string

    The name of the FileStorageAccount (for logging/display purposes).

    providerName: "Google Drive" = 'Google Drive'

    The name of this storage provider, used in error messages

    Accessors

    • get AccountId(): string

      Gets the account ID this driver instance is operating for. Returns undefined if the driver was not initialized with an account.

      Returns string

    • get AccountName(): string

      Gets the account name this driver instance is operating for. Returns undefined if the driver was not initialized with an account.

      Returns string

    • get IsConfigured(): boolean

      Checks if Google Drive provider is properly configured. Returns true if all required OAuth credentials are present. Logs detailed error messages if configuration is incomplete.

      Returns boolean

    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

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

      // 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');
      }
    • Generates a pre-authenticated URL for downloading files from a storage provider.

      This method abstracts the process of generating download URLs across different storage providers, offering a unified interface for obtaining these URLs. When called with the name of the file or object to download, it creates a URL that includes necessary authentication tokens directly in the URL, allowing for secure access without requiring additional authentication at download time.

      Parameters

      • objectName: string

        The name of the object or file for which you want to generate a download URL. This is the name as it is known to the storage provider, and it will be used to locate the file and generate the URL.

      Returns Promise<string>

      A Promise that resolves to a string, which is the pre-authenticated download URL for the specified object or file. This URL can be used immediately for downloading the file without further authentication.

      const downloadUrl = await CreatePreAuthDownloadUrl("report.pdf");
      console.log(downloadUrl); // Use this URL to download your file directly

      If a ProviderKey was previously returned by CreatePreAuthUploadUrl, use that as the objectName instead of the object's natural name:

      const downloadUrl = await CreatePreAuthDownloadUrl(file.ProviderKey);
      console.log(downloadUrl); // Use this URL to download your file directly

      This method simplifies the process of securely sharing or accessing files stored in cloud storage by providing a direct, pre-authenticated link to the file. It's particularly useful in applications where files need to be accessed or shared without navigating through the storage provider's standard authentication flow each time.

    • 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

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

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

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

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

      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

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

      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');
      }
    • Streams a file's content from Google Drive, optionally honoring a byte range.

      Uses files.get({ fileId, alt: 'media' }, { responseType: 'stream', headers: { Range } }), which returns a Node.js readable stream — the file is never buffered fully in memory. The Drive media endpoint honors the HTTP Range header, so the inclusive Range is encoded via the shared BuildHttpRangeHeader. The streamed response doesn't reliably surface the total object size, so this method resolves size/content-type via GetObjectMetadata (mirroring the Box driver) and clamps the range to the object size.

      Google Workspace files (Docs/Sheets/Slides/Drawings) are not directly downloadable — they must be exported to a concrete format, which has no Range semantics — so streaming throws for those types. Callers should fall back to GetObject (which performs the export).

      Parameters

      Returns Promise<ObjectStreamResult>

      A Promise resolving to an ObjectStreamResult.

      Error if the file doesn't exist, is a Google Workspace file, or cannot be streamed.

    • Initialize Google Drive storage provider.

      Always call this method after creating an instance.

      Parameters

      • Optionalconfig: GoogleDriveConfig

        Optional. Omit to use env vars, provide to override with database creds.

      Returns Promise<void>

      Simple Deployment (Environment Variables)
      const storage = new GoogleDriveFileStorage(); // Constructor loads env vars
      await storage.initialize(); // No config - uses env vars
      await storage.ListObjects('/');
      Multi-Tenant (Database Credentials)
      const storage = new GoogleDriveFileStorage();
      await storage.initialize({
      accountId: '12345',
      accountName: 'Google Drive Account',
      clientID: '...',
      clientSecret: '...',
      refreshToken: '...',
      rootFolderID: 'optional-folder-id'
      });
    • 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

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

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

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

      • OptionalcontentType: string

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

      • Optionalmetadata: 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

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

      • Optionaloptions: FileSearchOptions

        Search options

      Returns Promise<FileSearchResultSet>

      Promise resolving to search results

      // 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/'
      });
    • 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

      UnsupportedOperationError with information about the unsupported method and provider