📜  google sheet 自动更新车 - TypeScript (1)

📅  最后修改于: 2023-12-03 14:41:36.380000             🧑  作者: Mango

Google Sheet 自动更新车 - TypeScript

在本文中,我们将使用 TypeScript 编写一个程序,该程序可以自动从 Google Sheet 中获取数据并更新车辆的信息。

准备工作

在编写 TypeScript 程序之前,我们需要进行一些准备工作。首先,我们需要安装以下工具:

  • Node.js
  • TypeScript

其次,我们需要创建一个 Google API 项目,并生成一个由 Google 分配的 OAuth2 客户端 ID 和密钥。我们还需要在该项目中启用 Google Sheets API。

最后,我们需要创建一个 Google Sheet,并为其添加一个标题行和一些数据行,以便我们可以使用我们的程序来访问和更新这些数据。

编写程序

在进行上述准备工作之后,我们可以开始编写 TypeScript 程序了。我们需要使用以下依赖项:

  • google-auth-library
  • googleapis

我们可以使用 npm 来安装这些依赖项:

npm install google-auth-library googleapis

我们的程序将使用 OAuth2 客户端 ID 和密钥来进行身份验证,并使用 Google Sheets API 来访问和更新我们的 Google Sheet。以下是程序的主要部分:

import * as fs from 'fs';
import { google } from 'googleapis';
import { Credentials } from 'google-auth-library';

async function main() {
  const auth = await authorize({
    clientId: 'your-client-id',
    clientSecret: 'your-client-secret',
    credentialsFile: 'credentials.json',
    scopes: ['https://www.googleapis.com/auth/spreadsheets'],
  });

  const sheets = google.sheets({ version: 'v4', auth });
  const spreadsheetId = 'your-spreadsheet-id';
  const range = 'Sheet1!A2:C5';

  const response = await sheets.spreadsheets.values.get({
    spreadsheetId,
    range,
  });

  const values = response.data.values;

  console.log(values);
}

async function authorize(config: {
  clientId: string;
  clientSecret: string;
  credentialsFile: string;
  scopes: string[];
}): Promise<Credentials> {
  const credentials = JSON.parse(fs.readFileSync(config.credentialsFile, 'utf-8'));
  const { client_secret, client_id, redirect_uris } = credentials.web;

  const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

  try {
    const token = fs.readFileSync('token.json', 'utf-8');
    oAuth2Client.setCredentials(JSON.parse(token));
    return oAuth2Client;
  } catch (error) {
    const authUrl = oAuth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: config.scopes,
    });

    console.log(`Authorize this app by visiting this url: ${authUrl}`);

    const code = await new Promise<string>((resolve, reject) => {
      const readline = require('readline').createInterface({
        input: process.stdin,
        output: process.stdout,
      });

      readline.question('Enter the code from the authorization page here: ', (code) => {
        readline.close();
        resolve(code);
      });
    });

    const token = await oAuth2Client.getToken(code);

    fs.writeFileSync('token.json', JSON.stringify(token.tokens));
    return oAuth2Client;
  }
}

main().catch(console.error);

在这个程序中,我们首先调用 authorize 函数来进行身份验证。该函数将从指定的 credentials.json 文件中读取 OAuth2 客户端 ID 和密钥,并将使用指定的范围(https://www.googleapis.com/auth/spreadsheets)生成一个授权 URL。程序将在控制台输出该 URL,并等待用户将页面上的授权码输入到程序中。授权码将使用 OAuth2 客户端 ID 和密钥来交换令牌。令牌将保存在 token.json 文件中,并将在程序的下一次运行中重用。

当使用 authorize 函数获取了 auth 后,我们将使用 google.sheets API 从指定的 Google Sheet 中检索数据。在上面的例子中,我们正在检索 Sheet1 的 A2 到 C5 行。

总结

使用上述方法,我们可以轻松地从 TypeScript 中自动更新车辆信息。本文提供了一个简单的示例,您可以根据自己的需要进行扩展。