首页 > 解决方案 > 如何间歇性地检查已添加到 nodejs Google Tasks API 中任务列表的新任务?

问题描述

我一直在关注使用带有 node.js 的谷歌任务的快速入门:https ://developers.google.com/tasks/quickstart/nodejs并且已经开始获取任务列表,然后是其中的任务。但是,我想每隔设置的时间间隔检查任务列表并检索任何新的,然后将它们发送到我的网页以使用新任务对其进行更新。我不完全确定如何做到这一点。

const express = require('express');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const {google} = require('googleapis');

const app = express();
const directoryToServe = 'client';
const port = 3443;

app.use('/', express.static(path.join(__dirname, '..', directoryToServe)));
const httpsOptions = {
  cert: fs.readFileSync(path.join(__dirname, 'ssl', 'server.crt')),
  key: fs.readFileSync(path.join(__dirname, 'ssl', 'server.key'))
};


var inputs;

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/tasks'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Tasks API.
  authorize(JSON.parse(content), listTaskLists);

});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Lists the user's first 10 task lists.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listTaskLists(auth) {
  const service = google.tasks({version: 'v1', auth});
  service.tasklists.list({
    maxResults: 10,
  }, (err, res) => {
    if (err) return console.error('The API returned an error: ' + err);
    const taskLists = res.data.items;
    if (taskLists) {
      console.log('Task lists:');
      taskLists.forEach((taskList) => {
        console.log(`${taskList.title} (${taskList.id})`);

        getTasksFromTaskList(taskList.id, auth);
        //updateListTaskLists(taskList.title, taskList.id, auth);
      });
    } else {
      console.log('No task lists found.');
    }
  });
}

function getTasksFromTaskList(tasklistid, auth) {
  const service = google.tasks({version: 'v1', auth});
  service.tasks.list({
    tasklist: tasklistid,
  }, (err, res) => {
    if (err) return console.error('The API returned an error: ' + err);
    const tasks = res.data.items;
    if (tasks) {
      console.log(`Tasks from ${tasklistid}:`);
      tasks.forEach((task) => {
        inputs = {name: task.title};


        console.log(inputs);
        console.log(`${task.title} (${task.id})`);
      });
    } else {
      console.log('No tasks found.');
    }
  });
}


// Express route for incoming requests for a customer name
app.get('/inputs/', function(req, res) {
  console.log("send inputs: " + inputs);
  res.status(200).send(inputs);


});


// Express route for any other unrecognised incoming requests
app.get('*', function(req, res) {
  res.status(404).send('Unrecognised API call');
});

// Express route to handle errors
app.use(function(err, req, res, next) {
  if (req.xhr) {
    res.status(500).send('Oops, Something went wrong!');
  } else {
    next(err);
  }
});


var server = https.createServer(httpsOptions, app).listen(port, function () {
  console.log('Serving the ' + directoryToServe + '/ directory at https://localhost:' + port);
});

const io = require('socket.io').listen(server)

io.on('connection', function(socket) {
  // Here I want send the new tasks when a new one has been added
});

更新:

authorize(JSON.parse(content), listTaskLists);因此,我尝试使用 包装setInterval(authorize(JSON.parse(content), listTaskLists), 60000);来查看是否可以让它每分钟执行一次,作为它轮询 Google 任务以获取新添加任务的一种方式,但是我收到了这个错误:TypeError [ERR_INVALID_CALLBACK]:回调必须是一个函数。这是什么原因造成的?这也是使用 setInterval 的好方法吗?

标签: node.jsgoogle-api-nodejs-clientgoogle-tasks-apigoogle-tasks

解决方案


推荐阅读