存储 Google 日历中的事件列表 Node.js Express.js 应用程序中的示例

Store Events List from Google Calendar Node.js Example in Express.js Application

作为一名 javascript/node.js/express.js 新手,我正在努力解决这个问题。查看“Google Calendar API Node.js Quickstart”,我已经能够在 运行 node quickstart.js 时成功打印即将发生的事件列表。我现在想通过将这些数据传递到视图渲染器来在浏览器中呈现这些数据。我已经将 quickstart.js 中的代码复制到我的 routes/calendar.js 文件中。这是 routes/calendar.js 当前的样子:

var express = require('express');
var router = express.Router();

var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json';

/**
 * 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) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = 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 to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

function listEvents(auth) {
  var calendar = google.calendar('v3');
  calendar.events.list({
    auth: auth,
    calendarId: 'primary',
    timeMin: (new Date()).toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime'
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }

    var events = response.items;

    if (events.length == 0) {
      console.log('No upcoming events found.');
    } else {
      console.log('Upcoming 10 events:');
      for (var i = 0; i < events.length; i++) {
        var event = events[i];
        var start = event.start.dateTime || event.start.date;
        console.log('%s - %s', start, event.summary);
      }
    }
  });
}

/* GET events listing. */
router.get('/', function(req, res, next) {

  fs.readFile('client_secret.json', function processClientSecrets(err, content) {
    if (err) {
      console.log('Error loading client secret file: ' + err);
      return;
    }
    // Authorize a client with the loaded credentials, then call the
    // Google Calendar API.
    authorize(JSON.parse(content), listEvents);
  });

  // TODO:  How can I pass 'events' from 'listEvents' into the view renderer?
  res.render('calendar', { title: 'TS Calendar', current: 'calendar', events: events });
});

module.exports = router;

当我在浏览器中访问 http://localhost:3000/calendar 时,确实收到有关 'events' 未定义的错误,但我的控制台确实打印出日历事件,所以我知道它至少在工作一定程度。

在我看来,这只是一堆回调,我无法完全理解如何从 listEvents() 中 extract/store var events = response.items; 所以它在内部可用router.get()。有什么建议么?一个很好的例子就太棒了。

此外,为了奖励积分,我有点厌倦了将所有这些 logic/code 包含到 routes/calendar.js 文件中。是否有更 expressjs 风格或更合适的地方?

我想我在这里的心态是错误的。相反,我选择了客户端 javascript 并为此使用了 quickstart guide。我在这条路上取得了进展,但我有一种感觉,我很快就会发现它不会很好地适用于没有键盘进行身份验证的信息亭应用程序。当我说到那个点时可能需要问这个问题。