The getInfo
function takes a Google Sheet URL, authenticates with the Google Sheets API, and returns a structured object containing information about the spreadsheet and its sheets. This function is designed to be used by other parts of an application to access Google Sheet data.
npm run import -- "get google sheet info"
var importer = require('../Core');
var authorizeSheets = importer.import("authorize sheets api");
function getInfo(link) {
if(!link) {
throw new Error('You didn\'t specify a spreadsheet to work on.')
}
var docId = link.replace(/https:\/\/docs.google.com\/spreadsheets\/d\/|\/edit.*$|\/copy.*$/ig, '');
var sheets;
return authorizeSheets()
.then(s => sheets = s)
.then(() => sheets.spreadsheets.get({
spreadsheetId: docId
}))
.then(res => Object.assign(res.data, {
sheets: res.data.sheets.map(s => Object.assign(s, {
spreadsheetId: res.data.spreadsheetId
}))
}))
}
module.exports = getInfo;
const Core = require('../Core');
const { authorizeSheets } = Core.import('authorize sheets api');
/**
* Retrieves information about a Google Spreadsheet.
*
* @param {string} link - The link to the spreadsheet.
* @returns {Promise<Object>} A promise resolving to an object containing information about the spreadsheet.
*/
function getInfo(link) {
// Validate input
if (!link) {
throw new Error('You did not specify a spreadsheet to work on.');
}
// Extract spreadsheet ID from link
const docId = link.match(/https:\/\/docs\.google\.com\/spreadsheets\/d\/([a-zA-Z0-9-_]+)\//i)[1];
// Initialize variable to store spreadsheet object
let spreadsheet = null;
// Authenticate and retrieve spreadsheet data
return authorizeSheets()
.then((sheets) => {
// Set spreadsheet object
spreadsheet = sheets;
// Retrieve spreadsheet information
return spreadsheet.spreadsheets.get({
spreadsheetId: docId,
});
})
.then((res) => {
// Add spreadsheet ID to sheet metadata
const updatedRes = Object.assign(res.data, {
sheets: res.data.sheets.map((sheet) => Object.assign(sheet, {
spreadsheetId: res.data.spreadsheetId,
})),
});
// Return updated response
return updatedRes;
})
.catch((error) => {
// Log and rethrow error
console.error('Error retrieving spreadsheet information:', error);
throw error;
});
}
module.exports = getInfo;
This code defines a function getInfo
that retrieves information about a Google Sheet given its URL.
Here's a breakdown:
Dependencies: It imports the authorizeSheets
function from a local module Core
, which likely handles authentication with the Google Sheets API.
getInfo
Function:
link
) as input.authorizeSheets
to obtain an authorized client for interacting with the Google Sheets API.spreadsheets.get
method to retrieve details about the spreadsheet using the extracted ID.Export: The getInfo
function is exported, allowing other parts of the application to use it to fetch Google Sheet data.
Let me know if you'd like a deeper dive into any specific part of the code!