减少授权请求

Reduce Auth Requests

我正在使用 google-api-nodejs-client 制作一些 node.js 脚本。

这是与 api 交互的基本身份验证请求:

const { google } = require("googleapis");
const auth = new google.auth.GoogleAuth({
  keyFile: "credentials.json",
  scopes: "https://www.googleapis.com/auth/spreadsheets",
});
const getAuthClient = async () => {
  try {
    return await auth.getClient();
  } catch (error) {
    console.error(error);
  }
};

const sheetsClient = async () => {
  const client = await getAuthClient();
  return await google.sheets({ version: "v4", auth: client });
};

module.exports = { sheetsClient };

现在,每当我创建一个需要使用 sheetsClient 的函数时,我都需要像这样设置它(下面的示例是通用示例,我将对 api 进行其他调用我需要在哪里获取工作表客户端。在某些情况下,我需要在一个接一个调用的不同函数中读取(获取客户端)和写入(再次获取客户端):

const { google } = require("googleapis");
const { sheetsClient } = require("./googleAuth");

const createSheet = async (name) => {
    const client = await sheetsClient();
    const sheet = await client.spreadsheets.create({
        resource: {
            properties: {
                title,
            },
        },
    });
};

const updateSheet = async (name) => {
    const client = await sheetsClient();
    const sheet = await client.spreadsheets.update({
        resource: {
            properties: {
                title,
            },
        },
    });
};

const deleteSheet = async (name) => {
    const client = await sheetsClient();
    const sheet = await client.spreadsheets.delete({
        resource: {
            properties: {
                title,
            },
        },
    });
};

有没有更好的方法来访问客户端而不必在函数中每次都调用它?

有很多可能性。

  1. 最简单的可能是在所有函数之外只调用一次。
const { google } = require("googleapis");
const { sheetsClient } = require("./googleAuth");

// globally defined
const client = ( async () => await sheetsClient())();

// rest of code
const createSheet = async (name) => {

    // deleted : const client = await sheetsClient();

    const sheet = await client.spreadsheets.create({
        resource: {
            properties: {
                title,
            },
        },
    });
};

这将在此 js 文件中创建一个全局客户端变量。 然后你可以从每个函数中删除它的声明。

代码仍然运行顺利,但只有一次验证。

  1. 处理您的问题的另一种方法是通过使用标志确保 auth 函数真的只执行一次。 (此解决方案与记忆有关)
var client = null;
const getAuthClient = async () => {
  if (client) return client;

  try {
    client = await auth.getClient();
    return client;
  } catch (error) {
    console.error(error);
  }
};