I develop a simple app which uses Google Sheets as database. So far I was only using it to get the rows and it was enough for me. But now I’d like to add the feature where user can search by sheets values. Unfortunately, I couldn’t find in docs or on the Internet any examples using batchGet
method for that. It allows only to specify ranges and fetch such content - not by keyword. I found some examples with Query API
but, I think, it isn’t compatible with approach I provided below.
So, my question is: can I search and get some specific rows by keyword using batchGet()
? Or at least extend the provided code as much as possible, without rewriting everything?
const { google } = require('googleapis');
const client = new google.auth.JWT(
process.env.GS_CLIENT_EMAIL,
null,
process.env.GS_PRIVATE_KEY.replace(/\\n/g, '\n'),
['https://www.googleapis.com/auth/spreadsheets.readonly']
);
client.authorize((err) => {
if(err) {
console.log(err);
return;
}
return client;
});
const gsrun = async (lang, page) => {
const gsapi = google.sheets({ version: 'v4', auth: client });
const sheetId = lang.toUpperCase();
const spreadsheetId = process.env[`SHEET_${sheetId}`];
const fileInfo = await gsapi.spreadsheets.get({
spreadsheetId
});
const sheetNames = (page === null) ? fileInfo.data.sheets.map((d) => d.properties.title) : [fileInfo.data.sheets[page].properties.title];
const data = await gsapi.spreadsheets.values.batchGet({
spreadsheetId,
ranges: sheetNames.map((name) => `${name}!A1:D200`)
});
const sheetValues = data.data.valueRanges.map(({ values }) => values);
return {
totalPages: fileInfo.data.sheets.length,
items: sheetValues
}; // [[[],[],...[]],[[],[],...[]],...[],[],...[]];
};
exports.gsrun = gsrun;