Creates a new instance of GoogleDriveFileStorage.
Initializes the connection to Google Drive using either a service account key file or credentials provided directly in environment variables. Throws an error if neither authentication method is properly configured.
Private Optional _clientIDOAuth2 credentials for configuration checking
Private Optional _clientPrivate _driveThe Google Drive API client
Private Optional _refreshPrivate Optional _rootOptional root folder ID to restrict operations to a specific folder
Protected Readonly providerThe name of this storage provider, used in error messages
Checks if Google Drive provider is properly configured. Returns true if all required OAuth credentials are present.
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.
The path to the file to copy
The path where the copy should be created
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.
The path of the directory to create
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');
}
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.
The path to the file to download
A Promise resolving to the download URL
Error if the file cannot be found or the URL creation fails
// 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);
Creates a pre-authenticated upload URL for an object in Google Drive.
Google Drive doesn't directly support pre-signed upload URLs in the same way as other storage providers like S3 or Azure. Instead, uploads should be performed using the PutObject method.
The name of the object to upload
UnsupportedOperationError as this operation is not supported
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.
The path of the directory to delete
If true, deletes all contents recursively (default: false)
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.
The path to the file to delete
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.
The path of the directory to check
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.
Object identifier (prefer objectId for performance, fallback to fullPath)
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.
Object identifier (prefer objectId for performance, fallback to fullPath)
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');
}
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.
The path to the directory to list
Delimiter character (unused in Google Drive implementation)
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.
The current path of the object
The new path for the object
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.
The path to the file to check
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.
The path to the file to upload
The Buffer containing the data to upload
Optional contentType: stringOptional 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)
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:
Content search is always enabled for supported file types (Docs, Sheets, PDFs, etc.) when searchContent option is true.
Search query using Google Drive search syntax
Optional options: FileSearchOptionsSearch options
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/'
});
Private _escapePrivate _filePrivate 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.
The Google Drive file object to convert
The parent path to use for constructing the full path
A StorageObjectMetadata representation of the file
Private _getPrivate _getPrivate 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.
The path to the file or folder to find
A Promise resolving to the Google Drive file object
Error if the path cannot be found
Private _getPrivate 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.
The path to the folder to find or create
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.
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
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:
Optionally, you can set:
Example