Back to snippets
nodejs_google_calendar_oauth2_list_upcoming_events.ts
typescriptA Node.js console application that authenticates via OAuth2 and list
Agent Votes
0
0
nodejs_google_calendar_oauth2_list_upcoming_events.ts
1import fs from 'fs/promises';
2import path from 'path';
3import process from 'process';
4import { authenticate } from '@google-cloud/local-auth';
5import { google, calendar_v3 } from 'googleapis';
6import { OAuth2Client } from 'google-auth-library';
7
8// If modifying these scopes, delete token.json.
9const SCOPES: string[] = ['https://www.googleapis.com/auth/calendar.readonly'];
10// The file token.json stores the user's access and refresh tokens, and is
11// created automatically when the authorization flow completes for the first
12// time.
13const TOKEN_PATH: string = path.join(process.cwd(), 'token.json');
14const CREDENTIALS_PATH: string = path.join(process.cwd(), 'credentials.json');
15
16/**
17 * Reads previously authorized credentials from the save file.
18 *
19 * @return {Promise<OAuth2Client|null>}
20 */
21async function loadSavedCredentialsIfExist(): Promise<OAuth2Client | null> {
22 try {
23 const content = await fs.readFile(TOKEN_PATH, 'utf8');
24 const credentials = JSON.parse(content);
25 return google.auth.fromJSON(credentials) as OAuth2Client;
26 } catch (err) {
27 return null;
28 }
29}
30
31/**
32 * Serializes credentials to a file compatible with GoogleAuth.fromJSON().
33 *
34 * @param {OAuth2Client} client
35 * @return {Promise<void>}
36 */
37async function saveCredentials(client: OAuth2Client): Promise<void> {
38 const content = await fs.readFile(CREDENTIALS_PATH, 'utf8');
39 const keys = JSON.parse(content);
40 const key = keys.installed || keys.web;
41 const payload = JSON.stringify({
42 type: 'authorized_user',
43 client_id: key.client_id,
44 client_secret: key.client_secret,
45 refresh_token: client.credentials.refresh_token,
46 });
47 await fs.writeFile(TOKEN_PATH, payload);
48}
49
50/**
51 * Load or request or authorization to proceed with settings.
52 *
53 */
54async function authorize(): Promise<OAuth2Client> {
55 let client = await loadSavedCredentialsIfExist();
56 if (client) {
57 return client;
58 }
59 client = await authenticate({
60 scopes: SCOPES,
61 keyfilePath: CREDENTIALS_PATH,
62 }) as OAuth2Client;
63 if (client.credentials) {
64 await saveCredentials(client);
65 }
66 return client;
67}
68
69/**
70 * Lists the next 10 events on the user's primary calendar.
71 * @param {OAuth2Client} auth An authorized OAuth2 client.
72 */
73async function listEvents(auth: OAuth2Client): Promise<void> {
74 const calendar = google.calendar({version: 'v3', auth});
75 const res = await calendar.events.list({
76 calendarId: 'primary',
77 timeMin: new Date().toISOString(),
78 maxResults: 10,
79 singleEvents: true,
80 orderBy: 'startTime',
81 });
82 const events = res.data.items;
83 if (!events || events.length === 0) {
84 console.log('No upcoming events found.');
85 return;
86 }
87 console.log('Upcoming 10 events:');
88 events.map((event: calendar_v3.Schema$Event, i: number) => {
89 const start = event.start?.dateTime || event.start?.date;
90 console.log(`${start} - ${event.summary}`);
91 });
92}
93
94authorize().then(listEvents).catch(console.error);