googleapis / google-api-nodejs-client

Google's officially supported Node.js client library for accessing Google APIs. Support for authorization and authentication with OAuth 2.0, API Keys and JWT (Service Tokens) is included.
https://googleapis.dev/nodejs/googleapis/latest/
Apache License 2.0
11.27k stars 1.91k forks source link

React cache with google sheet apis (next.js) #3383

Closed dbertella closed 7 months ago

dbertella commented 8 months ago

Hi all I'm trying to build a small project with next.js and google sheet apis. I want to be able to use my method in different server components and I was hoping I could rely on the cache that react library expose. This is the reference to the documentation https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating

Unfortunately it doesn't seem to be working as expected, every time one of my route containing this function is visited new api calls are fired.

This is what I'm trying to cache with no luck:

import { google } from 'googleapis';
import { camelCase } from 'lodash';
import { cache } from 'react'

export const getDataFromSheet = cache(async (spreadsheetId: string, sheetName: string): Promise<Record<string, string>[]> => {
    try {
        const target = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
        const jwt = new google.auth.JWT(
            process.env.GOOGLE_SHEETS_CLIENT_EMAIL,
            undefined,
            `${process.env.GOOGLE_SHEETS_PRIVATE_KEY}`.replace(/\\n/g, '\n'),
            target
        );
        const sheets = google.sheets({ version: 'v4', auth: jwt });
        const response = await sheets.spreadsheets.values.get({
            spreadsheetId: spreadsheetId,
            range: sheetName
        });

        const rows = response.data.values;
        if (rows?.length) {
            const header = rows.shift()
            return rows.map((row) => Object.fromEntries(row.map((element, i) => [camelCase(header?.[i]), element])));
        }
    } catch (err) {
        console.log(err);
    }
    return [];
})

If you have any clue or any tip it will be really appreciated

dbertella commented 7 months ago

It turned out react cache doesn't do what I was expecting to do while using unstable_cache from next/cache does. Closing this because it's probably not relevant here, but maybe someone else will stamp on the same issue in the future