CVBora / services /googleDocsService.js
ismizo's picture
Upload 17 files
ccc6848 verified
Raw History Blame Contribute Delete
4.83 kB
const { google } = require('googleapis');
const { Readable } = require('stream');
const path = require('path');
const fs = require('fs');
/**
* Build an authenticated Google Drive client using a Service Account.
* Credentials can be supplied as:
* - GOOGLE_SERVICE_ACCOUNT_JSON (the full JSON string, good for env-var deployments)
* - GOOGLE_SERVICE_ACCOUNT_KEY_PATH (path to the JSON key file)
*/
function getDriveClient() {
let credentials;
if (process.env.GOOGLE_SERVICE_ACCOUNT_JSON) {
// Preferred for cloud deployments: full JSON embedded in env var
credentials = JSON.parse(process.env.GOOGLE_SERVICE_ACCOUNT_JSON);
} else if (process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH) {
const keyPath = path.resolve(process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH);
credentials = JSON.parse(fs.readFileSync(keyPath, 'utf8'));
} else {
return null; // Credentials not configured β€” caller should fall back
}
const auth = new google.auth.GoogleAuth({
credentials,
scopes: [
// drive.file only covers files created by the app in its own Drive.
// We need the broader 'drive' scope to write into a folder shared by another user.
'https://www.googleapis.com/auth/drive',
],
});
return google.drive({ version: 'v3', auth });
}
/**
* Converts an HTML string to a DOCX buffer via the Google Drive API.
*
* Flow:
* 1. Upload HTML β†’ Google Drive with MIME type conversion β†’ Google Doc
* 2. Export Google Doc β†’ DOCX buffer
* 3. Delete the temporary Google Doc immediately
*
* @param {string} html - Complete standalone HTML document
* @param {string} [title] - Optional document title
* @returns {Promise<Buffer>} DOCX file buffer
* @throws {Error} if Drive API is unreachable or credentials are missing
*/
async function convertHtmlToDocxViaGoogleDrive(html, title = 'CVBora Document') {
const drive = getDriveClient();
if (!drive) {
throw new Error('Google Drive credentials not configured. Set GOOGLE_SERVICE_ACCOUNT_JSON or GOOGLE_SERVICE_ACCOUNT_KEY_PATH.');
}
let fileId = null;
try {
// ── Step 1: Upload HTML β†’ Google Docs (Drive converts it automatically) ──
// If GOOGLE_DRIVE_FOLDER_ID is set, the file is created inside that shared
// folder and counts against the folder-owner's quota (not the service account's).
const htmlStream = Readable.from([html]);
const fileMetadata = {
name: title,
mimeType: 'application/vnd.google-apps.document', // triggers HTML β†’ Google Doc conversion
};
const folderId = process.env.GOOGLE_DRIVE_FOLDER_ID;
if (folderId) {
fileMetadata.parents = [folderId];
console.log(`πŸ“ Uploading into shared folder: ${folderId}`);
}
const uploadRes = await drive.files.create({
requestBody: fileMetadata,
media: {
mimeType: 'text/html',
body: htmlStream,
},
fields: 'id',
// supportsAllDrives allows writing into Shared Drives (Team Drives) too
supportsAllDrives: true,
});
fileId = uploadRes.data.id;
console.log(`πŸ“„ Google Doc created: ${fileId}`);
// ── Step 2: Export as DOCX ───────────────────────────────────────────────
const exportRes = await drive.files.export(
{
fileId,
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
},
{ responseType: 'arraybuffer' }
);
const docxBuffer = Buffer.from(exportRes.data);
console.log(`βœ… DOCX exported (${docxBuffer.length} bytes)`);
return docxBuffer;
} finally {
// ── Step 3: Always delete the temp file from Drive ──────────────────────
if (fileId) {
try {
await drive.files.delete({ fileId, supportsAllDrives: true });
console.log(`πŸ—‘οΈ Temp Google Doc deleted: ${fileId}`);
} catch (deleteErr) {
// Non-fatal β€” log but don't throw
console.warn(`⚠️ Could not delete temp Google Doc ${fileId}:`, deleteErr.message);
}
}
}
}
/**
* Returns true if Google Drive credentials are configured in the environment.
*/
function isGoogleDriveConfigured() {
return !!(process.env.GOOGLE_SERVICE_ACCOUNT_JSON || process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH);
}
module.exports = { convertHtmlToDocxViaGoogleDrive, isGoogleDriveConfigured };