我正在使用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 文件中创建一个全局客户端变量。那么你可以从每个函数中删除它的声明。
代码仍然可以顺利运行,但只有一个身份验证。
var client = null;
const getAuthClient = async () => {
if (client) return client;
try {
client = await auth.getClient();
return client;
} catch (error) {
console.error(error);
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句