2016-10-28 2 views
1

javascript/node.js/express.js 초보자로서이 기사에서 내 머리를 짚어보고자합니다. "Google Calendar API Node.js Quickstart"을 보면 node quickstart.js을 실행할 때 다가오는 이벤트 목록을 성공적으로 인쇄 할 수있었습니다. 이 데이터를 뷰 렌더러에 전달하여 브라우저에 표시하려고합니다. quickstart.js의 코드를 routes/calendar.js 파일로 복사했습니다. 내 브라우저에서 http://localhost:3000/calendar를 방문 할 때Google 캘린더 Node.js의 이벤트 목록 저장 Express.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; 

, 나는 '이벤트'정의되지 대한 오류를받을 수 있나요,하지만 내 콘솔 달력을 인쇄 않습니다이 경로가/calendar.js 현재 모습입니다 이벤트, 그래서 적어도 그것이 어떤 수준에서 작동하는지 알 수 있습니다.

콜백의 혼란으로 보입니다. var events = response.items;listEvents()에서 추출/저장하는 방법에 대해 머리를 감쌀 수 없으므로 router.get() 내에 사용할 수 있습니다. 어떤 제안? 좋은 예가 환상적 일 것입니다.

또한 보너스 포인트로이 모든 로직/코드를 routes/calendar.js 파일에 포함하는 데 약간의 어려움이 있습니다. 더 많은 expressjs-esque 또는 적절한 장소가 있습니까?

답변

0

나는 잘못된 생각을하고 있다고 생각합니다. 대신 클라이언트 측 자바 스크립트를 사용하여 quickstart guide을 사용했습니다. 나는이 길로 나아 갔지만, 키보드가 인증되지 않은 키오스크 애플리케이션에 잘 적응하지 못한다는 것을 빨리 알게 될 것 같은 느낌이 든다. 그 시점에 이르면 그 질문을 할 필요가 있습니다.

관련 문제