
Security News
TC39 Advances 11 Proposals for Math Precision, Binary APIs, and More
TC39 advances 11 JavaScript proposals, with two moving to Stage 4, bringing better math, binary APIs, and more features one step closer to the ECMAScript spec.
nestjs-google-drive-sdk
Advanced tools
Production-ready NestJS module for Google Drive integration with comprehensive file management capabilities
src/
├── interfaces/ # TypeScript interfaces and types
├── services/ # Core GoogleDriveService implementation
├── errors/ # Custom error classes
├── constants/ # Module constants and configuration
├── utils/ # Utility functions (validation, MIME detection, etc.)
├── google-drive.module.ts # NestJS dynamic module
└── index.ts # Main exports
This modular structure allows for easy extension and maintenance.
npm install nestjs-google-drive-sdk
import { Module } from '@nestjs/common';
import { GoogleDriveModule } from 'nestjs-google-drive-sdk';
@Module({
imports: [
GoogleDriveModule.forRoot({
credentials: {
client_id: 'your-client-id',
client_secret: 'your-client-secret',
redirect_uris: ['http://localhost:3000/auth/google/callback'],
},
// Optional: Default folder ID for uploads
defaultFolderId: 'your-default-folder-id',
}),
],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
import { GoogleDriveService } from 'nestjs-google-drive-sdk';
import { createReadStream } from 'fs';
@Injectable()
export class FileService {
constructor(private readonly googleDriveService: GoogleDriveService) {}
async uploadFile(filePath: string, fileName: string) {
const fileStream = createReadStream(filePath);
const result = await this.googleDriveService.uploadFile(fileStream, {
name: fileName,
mimeType: 'application/pdf', // Optional: auto-detected if not provided
});
console.log(`File uploaded: ${result.id}`);
console.log(`Download URL: ${result.downloadUrl}`);
return result;
}
async downloadFile(fileId: string) {
const stream = await this.googleDriveService.downloadFile(fileId);
return stream;
}
async getFileInfo(fileId: string) {
const metadata = await this.googleDriveService.getFileMetadata(fileId);
console.log(`File: ${metadata.name} (${metadata.size} bytes)`);
return metadata;
}
async testConnection() {
const isConnected = await this.googleDriveService.testConnection();
console.log(`Google Drive connection: ${isConnected ? 'OK' : 'Failed'}`);
return isConnected;
}
}
GoogleDriveModule.forRoot({
clientId: 'your-google-client-id',
clientSecret: 'your-google-client-secret',
redirectUri: 'your-redirect-uri',
refreshToken: 'your-refresh-token',
accessToken: 'your-access-token', // optional
scope: ['https://www.googleapis.com/auth/drive.file'], // optional
})
import { ConfigModule, ConfigService } from '@nestjs/config';
GoogleDriveModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
clientId: configService.get('GOOGLE_CLIENT_ID'),
clientSecret: configService.get('GOOGLE_CLIENT_SECRET'),
redirectUri: configService.get('GOOGLE_REDIRECT_URI'),
refreshToken: configService.get('GOOGLE_REFRESH_TOKEN'),
}),
inject: [ConfigService],
})
// Make the module available globally
GoogleDriveModule.forRootGlobal({
// ... configuration
})
// Or with async configuration
GoogleDriveModule.forRootAsyncGlobal({
// ... async configuration
})
uploadFile(fileStream, options): Promise<UploadResult>
Upload a file to Google Drive.
interface UploadFileOptions {
name: string; // File name
parents?: string[]; // Parent folder IDs (optional)
mimeType?: string; // MIME type (auto-detected if not provided)
}
interface UploadResult {
id: string; // Google Drive file ID
name: string; // File name
mimeType: string; // MIME type
size: string; // File size in bytes
downloadUrl: string; // Direct download URL
// ... other metadata
}
downloadFile(fileId): Promise<Readable>
Download a file from Google Drive as a readable stream.
getFileMetadata(fileId): Promise<FileMetadata>
Get file metadata including name, size, MIME type, creation/modification dates.
testConnection(): Promise<boolean>
Test connection to Google Drive API. Returns true
if connected successfully.
The module exports helpful utility functions:
import {
validateFileName,
getMimeTypeFromExtension,
formatFileSize,
bufferToStream
} from 'nestjs-google-drive-sdk';
// Validate file name (checks for invalid characters)
const isValid = validateFileName('my-file.pdf'); // true
// Get MIME type from file extension
const mimeType = getMimeTypeFromExtension('document.pdf'); // 'application/pdf'
// Format file size in human-readable format
const formatted = formatFileSize(1048576); // '1 MB'
// Convert Buffer to Readable stream
const stream = bufferToStream(buffer);
The module provides specific error classes:
import {
FileUploadError,
FileDownloadError,
AuthenticationError,
ConfigurationError
} from 'nestjs-google-drive-sdk';
try {
await googleDriveService.uploadFile(stream, options);
} catch (error) {
if (error instanceof FileUploadError) {
console.error('Upload failed:', error.message, error.fileName);
} else if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof ConfigurationError) {
console.error('Configuration error:', error.message);
}
}
Detailed guide: Google Drive API Quickstart
import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
@Controller('files')
export class FilesController {
constructor(private readonly googleDriveService: GoogleDriveService) {}
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
async uploadFile(@UploadedFile() file: Express.Multer.File) {
const result = await this.googleDriveService.uploadFile(file.buffer, {
name: file.originalname,
mimeType: file.mimetype,
});
return {
success: true,
fileId: result.id,
downloadUrl: result.downloadUrl,
};
}
}
@Get('download/:fileId')
async downloadFile(
@Param('fileId') fileId: string,
@Res() res: Response
) {
try {
const stream = await this.googleDriveService.downloadFile(fileId);
const metadata = await this.googleDriveService.getFileMetadata(fileId);
res.setHeader('Content-Type', metadata.mimeType);
res.setHeader('Content-Disposition', `attachment; filename="${metadata.name}"`);
stream.pipe(res);
} catch (error) {
res.status(404).json({ error: 'File not found' });
}
}
MIT License - see the LICENSE file for details.
FAQs
Production-ready NestJS module for Google Drive integration with comprehensive file management capabilities
The npm package nestjs-google-drive-sdk receives a total of 1 weekly downloads. As such, nestjs-google-drive-sdk popularity was classified as not popular.
We found that nestjs-google-drive-sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
TC39 advances 11 JavaScript proposals, with two moving to Stage 4, bringing better math, binary APIs, and more features one step closer to the ECMAScript spec.
Research
/Security News
A flawed sandbox in @nestjs/devtools-integration lets attackers run code on your machine via CSRF, leading to full Remote Code Execution (RCE).
Product
Customize license detection with Socket’s new license overlays: gain control, reduce noise, and handle edge cases with precision.