2024-09-18 19:54:31 +05:30
|
|
|
import { google } from "googleapis";
|
|
|
|
|
import fs from 'fs';
|
|
|
|
|
import path from 'path';
|
2024-09-19 17:42:20 +05:30
|
|
|
import logger from "../../logger";
|
2024-09-18 19:54:31 +05:30
|
|
|
|
|
|
|
|
export async function writeDataToSheet(spreadsheetId: string, range: string, data: any[]) {
|
|
|
|
|
try {
|
2024-09-19 17:42:20 +05:30
|
|
|
const integrationCredentialsPath = path.join(__dirname, 'integrations.json');
|
|
|
|
|
const integrationCredentials = JSON.parse(fs.readFileSync(integrationCredentialsPath, 'utf-8'));
|
2024-09-18 19:54:31 +05:30
|
|
|
|
|
|
|
|
const auth = new google.auth.GoogleAuth({
|
|
|
|
|
credentials: {
|
2024-09-19 17:42:20 +05:30
|
|
|
client_email: integrationCredentials.credentials.client_email,
|
|
|
|
|
private_key: integrationCredentials.credentials.private_key,
|
2024-09-18 19:54:31 +05:30
|
|
|
},
|
|
|
|
|
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const authToken = await auth.getClient();
|
|
|
|
|
const sheets = google.sheets({ version: 'v4', auth: authToken as any });
|
|
|
|
|
|
|
|
|
|
const resource = { values: data };
|
|
|
|
|
|
|
|
|
|
await sheets.spreadsheets.values.append({
|
|
|
|
|
spreadsheetId,
|
|
|
|
|
range,
|
|
|
|
|
valueInputOption: 'USER_ENTERED',
|
|
|
|
|
requestBody: resource,
|
|
|
|
|
});
|
|
|
|
|
|
2024-09-19 17:42:20 +05:30
|
|
|
logger.log(`info`, `Data written to Google Sheet: ${spreadsheetId}, Range: ${range}`);
|
2024-09-18 22:05:06 +05:30
|
|
|
} catch (error: any) {
|
2024-09-19 17:42:20 +05:30
|
|
|
logger.log(`error`, `Error writing data to Google Sheet: ${error.message}`);
|
2024-09-18 19:54:31 +05:30
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|