node.js - 减少身份验证请求
问题描述
我正在使用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,
},
},
});
};
有没有更好的方法来访问客户端而不必每次在函数中调用它?
解决方案
有很多可能性。
- 最简单的可能是在所有函数之外只调用一次。
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 文件中创建一个全局客户端变量。然后你可以从每个函数中删除它的声明。
代码仍将顺利运行,但只会进行一次身份验证。
- 处理您的问题的另一种方法是通过使用标志确保 auth 函数确实只执行一次。(此解决方案与记忆有关)
var client = null;
const getAuthClient = async () => {
if (client) return client;
try {
client = await auth.getClient();
return client;
} catch (error) {
console.error(error);
}
};
推荐阅读
- python - 列出熊猫数据框 - Python
- php - PHP - 无法访问数组,因为“février”与“février”不同
- servicestack - ServiceStack中是否有可能有两个BaseURL WebHostUrl?
- shell - 如何使用 shell 脚本从 url 中删除主机详细信息
- cron - 如何解决“没有 SELinux 安全上下文 (/etc/crontab)”的问题?
- deep-learning - 在 Linux 中使用 fastText 预测语言的命令
- csvhelper - CsvHelper 可以处理“[[0,0],[100,100]]”这样的数据吗?
- sql - 相同的列值不同的行到不同的列值不同的行
- javascript - 如何在 Jest 测试的覆盖范围内避免 WebStorm 标记注释?
- java - 当java中的switch语句中没有赋值时会发生什么?