Creates a new SharePointFileStorage instance
This constructor reads configuration from environment variables if available. If no environment variables are set, the provider can be initialized later via the initialize() method with OAuth credentials from the database.
Protected_The ID of the FileStorageAccount this driver instance is operating for. Set during initialization via the config parameter.
Protected_The name of the FileStorageAccount (for logging/display purposes).
Protected ReadonlyproviderThe name of this storage provider
Gets the account ID this driver instance is operating for. Returns undefined if the driver was not initialized with an account.
Gets the account name this driver instance is operating for. Returns undefined if the driver was not initialized with an account.
Checks if SharePoint provider is properly configured. Returns true if the Graph client is initialized and has required IDs. Logs detailed error messages if configuration is incomplete.
SharePoint supports ranged streaming: the Microsoft Graph driveItem @microsoft.graph.downloadUrl
is a short-lived pre-authenticated URL that honors the HTTP Range header.
Copies a file from one location to another
This method creates a copy of a file at a new location. The original file remains unchanged.
Path to the source file (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
Creates a directory (folder) in SharePoint
This method creates a new folder at the specified path. The parent directory must already exist.
Path where the directory should be created (e.g., 'documents/new-folder')
A Promise that resolves to true if successful, false if an error occurs
// Create a new folder
const createResult = await storage.CreateDirectory('documents/2024-reports');
if (createResult) {
console.log('Folder created successfully');
// Now we can put files in this folder
await storage.PutObject(
'documents/2024-reports/q1-results.xlsx',
fileContent,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
);
} else {
console.error('Failed to create folder');
}
Creates a pre-authenticated download URL for an object
This method generates a time-limited, publicly accessible URL that can be used to download a file without authentication. The URL expires after 10 minutes.
Path to the object to create a download URL for (e.g., 'documents/report.pdf')
A Promise that resolves to the pre-authenticated download URL
// Generate a pre-authenticated download URL that will work for 10 minutes
const downloadUrl = await storage.CreatePreAuthDownloadUrl('presentations/quarterly-update.pptx');
console.log(`Download the file using this URL: ${downloadUrl}`);
// You can share this URL with users who don't have SharePoint access
// The URL will expire after 10 minutes
Creates a pre-authenticated upload URL (not supported in SharePoint)
This method is not supported for SharePoint storage as SharePoint 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
// 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 SharePoint.');
// Use PutObject instead
await storage.PutObject('documents/report.docx', fileContent, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
}
}
Deletes a directory (folder) and optionally its contents
This method deletes a folder from SharePoint. By default, it will only delete empty folders unless the recursive parameter is set to true.
Path to the directory to delete (e.g., 'archive/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');
// 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 an object (file) from SharePoint
This method permanently deletes a file from SharePoint storage. Note that deleted files may be recoverable from the SharePoint recycle bin depending on your SharePoint configuration.
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
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, 'application/pdf');
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
try {
// Fast path: Use objectId (SharePoint item ID)
const fileContent = await storage.GetObject({ objectId: '01BYE5RZ6QN3VYRVNHHFDK2QJODWDDFR4E' });
// 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 a local file
// 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
try {
// Fast path: Use objectId (SharePoint item ID)
const metadata = await storage.GetObjectMetadata({ objectId: '01BYE5RZ6QN3VYRVNHHFDK2QJODWDDFR4E' });
// Slow path: Use path
const metadata2 = await storage.GetObjectMetadata({ fullPath: 'presentations/quarterly-update.pptx' });
console.log(`Name: ${metadata.name}`);
console.log(`Size: ${metadata.size} bytes`);
console.log(`Content Type: ${metadata.contentType}`);
console.log(`Last Modified: ${metadata.lastModified}`);
console.log(`Is Directory: ${metadata.isDirectory}`);
} catch (error) {
console.error('Error getting metadata:', error.message);
}
Streams a file's content from SharePoint, optionally honoring a byte range.
Resolves the driveItem (fast path via objectId, slow path via fullPath), reads its
@microsoft.graph.downloadUrl (a short-lived pre-authenticated URL), and fetches that URL
with the inclusive Range encoded via BuildHttpRangeHeader. The fetch response body is
a web ReadableStream, converted to a Node Readable via Readable.fromWeb so it is
never buffered fully in memory. Content-Type, Content-Length, and (for ranged reads)
Content-Range are read straight off the HTTP response headers, falling back to the item's
size for the total when the server doesn't return a Content-Range.
Object identifier (prefer objectId) plus optional Range.
A Promise resolving to an ObjectStreamResult.
Initialize SharePoint storage provider with optional configuration.
ALWAYS call this method after creating a provider instance.
Constructor loads credentials from environment variables, then call initialize() with no config to complete setup:
Optionalconfig: SharePointOAuthConfigConfiguration object containing OAuth2 credentials from database
Lists objects in a given directory (folder)
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')
Optionaldelimiter: stringOptional delimiter character (not used in this implementation)
A Promise that resolves to a StorageListResult containing objects and prefixes
objects array in the result 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
for (const obj of result.objects) {
console.log(`Name: ${obj.name}, Size: ${obj.size}, Type: ${obj.isDirectory ? 'Folder' : 'File'}`);
}
// Process subfolders
for (const prefix of result.prefixes) {
console.log(`Subfolder: ${prefix}`);
}
Moves an object from one location to another
This method moves a file or folder from one location in SharePoint to another. 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
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 SharePoint
This method uploads a file to SharePoint at the specified path. It automatically determines whether to use a simple upload or a chunked upload based on file size.
Path where the file should be uploaded (e.g., 'documents/report.pdf')
Buffer containing the file content
OptionalcontentType: stringOptional MIME type of the file (if not provided, it will be guessed from the filename)
Optionalmetadata: Record<string, string>Optional metadata to associate with the file (not used in SharePoint implementation)
A Promise that resolves to true if successful, false if an error occurs
// Create a text file
const textContent = Buffer.from('This is a sample document', 'utf8');
const uploadResult = await storage.PutObject(
'documents/sample.txt',
textContent,
'text/plain'
);
// 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,
'application/vnd.openxmlformats-officedocument.presentationml.presentation'
);
if (largeUploadResult) {
console.log('Large file uploaded successfully');
} else {
console.error('Failed to upload large file');
}
Search files in SharePoint using Microsoft Graph Search API.
This method provides powerful search capabilities using KQL (Keyword Query Language), SharePoint's native query language. The search can target file names, metadata, and optionally file contents.
The search query string. Can be plain text or use KQL syntax for advanced queries.
Optionaloptions: FileSearchOptionsOptional search configuration including filters, limits, and content search
A Promise resolving to FileSearchResultSet with matched files and pagination info
KQL Query Syntax Examples:
"quarterly report" - searches for files containing these terms"budget AND 2024", "draft OR final", "report NOT internal""proj*" matches "project", "projection", etc."FileType:pdf", "Author:John Smith", "Size>1000000""Created>=2024-01-01", "LastModifiedTime<2024-12-31""project NEAR report" - finds terms near each other"\"annual budget report\"" - exact phrase matchAdditional Filtering: The method automatically adds KQL filters based on the provided options:
fileTypes: Adds FileType filters (e.g., FileType:pdf OR FileType:docx)modifiedAfter/modifiedBefore: Adds LastModifiedTime filterspathPrefix: Adds Path filter to restrict search to a directorysearchContent: When false, restricts search to filename only// Simple text search in filenames
const results = await storage.SearchFiles('quarterly report', {
maxResults: 20
});
// Search for PDFs only
const pdfResults = await storage.SearchFiles('budget', {
fileTypes: ['pdf'],
maxResults: 50
});
// Search with date range
const recentResults = await storage.SearchFiles('meeting notes', {
modifiedAfter: new Date('2024-01-01'),
modifiedBefore: new Date('2024-12-31'),
searchContent: true
});
// Search within specific directory
const folderResults = await storage.SearchFiles('presentation', {
pathPrefix: 'documents/reports',
fileTypes: ['pptx', 'pdf']
});
// Advanced KQL query
const advancedResults = await storage.SearchFiles(
'FileType:xlsx AND Created>=2024-01-01 AND Author:"John Smith"',
{ maxResults: 100 }
);
ProtectedthrowHelper 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
FileStorageBase implementation for Microsoft SharePoint using the Microsoft Graph API
This provider allows working with files stored in SharePoint document libraries. It uses the Microsoft Graph API and client credentials authentication flow to securely access and manipulate SharePoint files and folders.
Remarks
This implementation requires the following environment variables:
To use this provider, you need to:
Example