How to export nested function as module - javascript

I'd like to export a nested function.
There is an authentication step and then a call to a service.
The auth step must be passed to the call to the service which is nested.
I'm following Google's basic code:
const fs = require(`fs`);
const readline = require(`readline`);
const {google} = require(`googleapis`);
require(`dotenv`).config();
module.exports = {
authFunction: function(params){ <--------------------------- Am currently exporting this
// If modifying these scopes, delete token.json.
const SCOPES = [`https://www.googleapis.com/auth/service`];
// 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 Service API.
authorize(JSON.parse(content), doStuff);
});
/**
* 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) => {
console.log(JSON.parse(token))
if (err) return getAccessToken(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 getAccessToken(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);
});
});
}
/**
* Do some stuff.
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function doStuff(auth) { <--------------Would like to make this async and export it form this module
const service = google.service({version: `v3`, auth});
service.object.dosomething({
auth: auth,
}, function(err, event) {
if (err) {
console.log(`There was an error contacting the service: ` + err);
return;
}
console.log(`Success`);
}, (err, res) => {
if (err) return console.log(`The API returned an error: ` + err);
});
}
},
};
I'd like to use async/await and make the doStuff an exported async function which I can call elsewhere.
I have tried everything obvious, such as moving the exports statement, assigning to variables etc.
How can I export doStuff as an async function, instead of authFunction?
Thank you

Related

Unable to get message contents of email using google API

I'm trying to write some code in order to retrieve an email message using Google APIs. I followed the documentation provided here: https://developers.google.com/gmail/api/reference/rest/v1/users.messages/get?apix_params=%7B%22userId%22%3A%22prashanthpillay2%40gmail.com%22%2C%22id%22%3A%22176d95971a2ffce1%22%7D, to implement my showMessageContent function and used the quickstart sample found here: https://developers.google.com/gmail/api/quickstart/nodejs?authuser=1, but when I execute the code I only get the message ID displayed and nothing about the actual message. Any help would be great, I'm pretty new to this stuff.
Entire Code for my index.js file:
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
let messageArr = [];
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
// 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('client_secret.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Gmail API.
authorize(JSON.parse(content), listMessages);
});
/**
* 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);
});
});
}
async function listMessages(auth) {
const gmail = google.gmail({version: 'v1', auth});
gmail.users.messages.list({
userId: 'me',
maxResults: 1
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const messages = res.data.messages;
if (messages) {
console.log('Messages:');
let i=0;
messages.forEach((message) => {
messageArr[i] = message.id;
console.log(messageArr[i]);
i++;
});
} else {
console.log('No messages found.');
}
});
setTimeout(() =>
{console.log(gmail.users.messages.get(
{
userId: 'me',
id: '176daac2fedbf7f9'
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
else{
return res;
}
})
);
}, 3000);
}
Problem function:
async function listMessages(auth) {
const gmail = google.gmail({version: 'v1', auth});
gmail.users.messages.list({
userId: 'me',
maxResults: 1
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const messages = res.data.messages;
if (messages) {
console.log('Messages:');
let i=0;
messages.forEach((message) => {
messageArr[i] = message.id;
console.log(messageArr[i]);
i++;
});
} else {
console.log('No messages found.');
}
});
setTimeout(() =>
{console.log(gmail.users.messages.get(
{
userId: 'me',
id: '176daac2fedbf7f9'
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
else{
return res;
}
})
);
}, 3000);
}
The result when I run it is in the attached picture
When the callback in setTimeout runs, it results in the result being undefined, which doesn't make sense to me since I passed the the correct ID manually to gmail.users.messages.get().

Return a result from node.js google drive api

I have a flow for uploading files to google drive using google drive API on a node.js server.
Everything works, the file is uploaded to a specific folder inside my google drive.
I created a file google-drive.js with all the function
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive'];
// 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';
function readFile(filePath) {
fs.readFile('./server/drive/credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.
// return authorize(JSON.parse(content), listFiles);
authorize(JSON.parse(content), filePath, uploadFile);
})
}
/**
* 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, filePath, callback) {
const {client_secret, client_id, redirect_uris} = credentials.web;
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 getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client, filePath);
});
}
/**
* 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 getAccessToken(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, filePath);
});
});
}
/**
* Lists the names and IDs of up to 10 files.
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
const drive = google.drive({version: 'v3', auth});
drive.files.list({
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const files = res.data.files;
if (files.length) {
console.log('Files:');
files.map((file) => {
console.log(`${file.name} (${file.id})`);
});
} else {
console.log('No files found.');
}
});
}
function uploadFile(auth, filePath) {
const drive = google.drive({version: 'v3', auth});
const folderMetaData = {
'name': 'TEST_FOLDER',
'mimeType': 'application/vnd.google-apps.folder'
};
return drive.files.create({
resource: folderMetaData,
fields: 'id'
}, function (err, file) {
if (err) {
console.log(err);
return err;
} else {
const folderId = file.data.id;
const fileMetadata = {
'name': 'TEST_IMAGE',
parents: [folderId]
};
const media = {
mimeType: 'image/jpeg',
body: fs.createReadStream(filePath)
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, (err, file) => {
if (err) {
// Handle error
return err;
} else {
return file;
}
});
}
})
}
module.exports = {
// Load client secrets from a local file.
read: function (filePath) {
return readFile(filePath);
}
};
and in my server.js (main file) i have imported the google-drive.js and added a route like this :
app.post('/api/drive/auth', async (req, res) => {
let result = null;
result = await drive.read(req.body.filePath);
console.log(result)
res.status(200).json('success');
});
the problem is, i can't seem to get a result from the flow of the uploading, everytime i console.log(result) i get undefined.
I would like to propose the following modification.
Modification point:
At googleapis for Node.js, drive.files.list and drive.files.create return Promise.
When this point is reflected to your script, it becomes as follows.
Modified script:
const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");
// If modifying these scopes, delete token.json.
const SCOPES = ["https://www.googleapis.com/auth/drive"];
// 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';
function readFile(filePath) {
return new Promise((resolve) => {
fs.readFile('./server/drive/credentials.json', (err, content) => {
if (err) return console.log("Error loading client secret file:", err);
// Authorize a client with credentials, then call the Google Drive API.
// authorize(JSON.parse(content), (auth) => resolve(listFiles(auth))); // <--- Modified. When you use "listFiles", please use this line.
authorize(JSON.parse(content), (auth) => resolve(uploadFile(auth, filePath))); // <--- Modified
});
});
}
/**
* 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.web;
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 getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client); // <--- Modified
});
}
/**
* 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 getAccessToken(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); // <--- Modified
});
});
}
/**
* Lists the names and IDs of up to 10 files.
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
async function listFiles(auth) { // <--- Modified
const drive = google.drive({ version: "v3", auth });
const res = await drive.files
.list({
pageSize: 10,
fields: "nextPageToken, files(id, name)",
})
.catch(console.log);
return res; // or return res.data;
}
async function uploadFile(auth, filePath) { // <--- Modified
const drive = google.drive({ version: "v3", auth });
const folderMetaData = {
name: "TEST_FOLDER",
mimeType: "application/vnd.google-apps.folder",
};
const res1 = await drive.files
.create({
resource: folderMetaData,
fields: "id",
})
.catch(console.log);
const folderId = res1.data.id;
const fileMetadata = {
name: "TEST_IMAGE",
parents: [folderId],
};
const media = {
mimeType: 'image/jpeg',
body: fs.createReadStream(filePath),
};
const res2 = await drive.files
.create({
resource: fileMetadata,
media: media,
fields: "id",
})
.catch(console.log);
return res2; // or return res2.data;
}
module.exports = {
// Load client secrets from a local file.
read: async function (filePath) {
return await readFile(filePath);
}, // <--- Modified
};
I think that in above modified script, your server.js can be used without modifying.
Note:
In your script, const { client_secret, client_id, redirect_uris } = credentials.web is used. If no error occurs, please use this. If an error occurs, please try to use const { client_secret, client_id, redirect_uris } = credentials.installed.
Reference:
googleapis for Node.js

I'm having trouble reading emails from Gmail using the Gmail API

I am listing all messages from the inbox, being able to view the IDs of each email, but I cannot send them by parameter to search for each email using the function: gmail.users.messages.get
Just return a message saying: undefined
Can anyone tell me why this is happening?
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
// 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 Gmail API.
authorize(JSON.parse(content), listLabels);
});
/**
* 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 labels in the user's account.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listLabels(auth) {
const gmail = google.gmail({version: 'v1', auth});
gmail.users.labels.list({
userId: 'me',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const labels = res.data.labels;
if (labels.length) {
console.log('Labels:');
labels.forEach((label) => {
console.log(`- ${label.name}`);
});
listMessages(auth);
} else {
console.log('No labels found.');
}
});
}
/************************** My code is below *******************************/
function listMessages(auth){
var gmail = google.gmail('v1');
gmail.users.messages.list({
auth: auth,
userId: 'me',
q : 'has:attachment',
labelIds: 'INBOX',
}, (err, res) => {
if(err){
console.log('Erro ao listar os emails');
}
var message = res;
Object.keys(message).forEach(index => {
console.log(res[index]);
gmail.users.messages.get({
userId: 'me',
id: message[index].id,
format: 'full',
}, (err, res) => {
console.log(res);
})
})
})
}
You want to retrieve the messages with gmail.users.messages.get using the values retrieved from gmail.users.messages.list.
You want to achieve this using googleapis with Node.js.
You have already been able to get the values from Gmail using Gmail API.
Modification points:
The values from gmail.users.messages.list can be retrieved with res.data. In your script, how about modifying from var message = res is modified to var messages = res.data.messages?
When you use auth: auth with gmail.users.messages.list, please also use it at gmail.users.messages.get.
I think that these points might be the reason of your issue. When above points are reflected to your script, it becomes as follows.
Modified script:
From:
var message = res;
Object.keys(message).forEach(index => {
console.log(res[index]);
gmail.users.messages.get({
userId: 'me',
id: message[index].id,
format: 'full',
}, (err, res) => {
console.log(res);
})
})
To:
var messages = res.data.messages;
messages.forEach((message) => {
gmail.users.messages.get(
{
auth: auth,
userId: "me",
id: message.id,
format: "full",
},
(err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res.data);
}
);
});
References:
googleapis for Node.js
Users.messages: get

Cannot read property 'forEach' of undefined with API

I want to request all classes then all assignments of those classes from google classroom. For the class listing part, I used google's example code, for the assignment listing I used my own. The code runs and does what it is expected to do, lists the assignments, however it outputs
Execute error TypeError: Cannot read property 'forEach' of undefined
at /home/daniel/nodegui-starter/src/index-nogui.ts:106:16
at processTicksAndRejections (internal/process/task_queues.js:97:5)
also. I have pasted the contents of the file below. as far as I understand it says that courseWork is undefined, but I define it just above!
Can anyone help me?
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly', 'https://www.googleapis.com/auth/classroom.coursework.me'];
// 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 Classroom API.
// authorize(JSON.parse(coExecute error TypeError: Cannot read property 'forEach' of undefined
at /home/daniel/nodegui-starter/src/index-nogui.ts:106:16
at processTicksAndRejections (internal/process/task_queues.js:97:5)ntent), listCourses);
authorize(JSON.parse(content), listCourses);
});
/**
* 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);
});
});
}
/*function listAssignments(auth, courseId) {
try {
const classroom = google.classroom({version: 'v1', auth});
classroom.courses.courseWork.list({
"courseId": courseId
}, (err, res) => {
if (err) return console.error('The API returned an error: ' + err);
const courseWork = res.data.courseWork;
res.data.courseWork.forEach((assignment) => {
if(assignment.dueDate){
console.log(`${assignment.title} (${assignment.alternateLink}) ${assignment.dueDate.year}. ${assignment.dueDate.month}. ${assignment.dueDate.day}`);
}
else {
console.log(`${assignment.title} (${assignment.alternateLink})`);
}
});
});
}
catch(error){
console.log("you have an error in your code and you better go and cry")
}
}
*/
function listAssignments(auth, courseId) {
const classroom = google.classroom({version: 'v1', auth});
return classroom.courses.courseWork.list({
"courseId": courseId
})
.then(function(response) {
var courseWork = response.data.courseWork;
courseWork.forEach(assignment => {
if (assignment.dueDate) {
console.log(`${assignment.title} (${assignment.alternateLink}) ${assignment.dueDate.year}. ${assignment.dueDate.month}. ${assignment.dueDate.day}`);
}
else {
console.log(`${assignment.title} (${assignment.alternateLink})`);
}
});
})
.catch(function(err) {
console.error("Execute error", err);
});
};
/**
* Lists the first 10 courses the user has access to.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listCourses(auth) {
const classroom = google.classroom({version: 'v1', auth});
classroom.courses.list({
pageSize: 100,
}, (err, res) => {
if (err) return console.error('The API returned an error: ' + err);
const courses = res.data.courses;
if (courses && courses.length) {
courses.forEach((course) => {
try {
listAssignments(auth,course.id)}
catch(error){
console.log("you have an error in your code and you better go and cry")
}
});
} else {
console.log('No courses found.');
}
});
}
I found the solution. I had a class where I had no courseWork yet, so I had to add a check at the beginning to check if courseWork exists.

How do I get the data that's printing to the console to store in a global variable?

What I am doing is pulling data from an Google Sheets spreadsheet and printing it to the console with rows.map. I want to be able to use that data that's printing to the console to manipulate and display on an HTML page.
What I was thinking was to store all of the values printing to the console into a global variable, that way I will be able to call that global variable on an HTML page. Just can't seem to find the solution. Any help?
const fs = require('fs');
const readline = require('readline');
const {
google
} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
// 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 Sheets API.
authorize(JSON.parse(content), listMajors);
});
/**
* 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 while trying to retrieve 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);
});
});
}
/**
* #param {google.auth.OAuth2} auth The authenticated Google OAuth client.
*/
function listMajors(auth) {
const sheets = google.sheets({
version: 'v4',
auth
});
sheets.spreadsheets.values.get({
spreadsheetId: '1O9FT3-p_knsbm8SIBznkDGHuL3LdfPaDnDJelqyBsqA',
range: 'Price Alerts',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
// Print columns A and E, which correspond to indices 0 and 4.
rows.map((row) => {
console.log(`${row[0]}, ${row[1]}, ${row[2]}`);
});
} else {
console.log('No data found.');
}
});
}

Categories