首页 > 解决方案 > 减少身份验证请求

问题描述

我正在使用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,
            },
        },
    });
};

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

标签: node.jsgoogle-api

解决方案


有很多可能性。

  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);
  }
};

推荐阅读