Skip to content

Instantly share code, notes, and snippets.

@mrzmyr
Created November 12, 2018 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrzmyr/c71e2f3dcd9a7a2b798a7d939bcdc468 to your computer and use it in GitHub Desktop.
Save mrzmyr/c71e2f3dcd9a7a2b798a7d939bcdc468 to your computer and use it in GitHub Desktop.
Google Sheets addRow and Authentication
// Go to https://developers.google.com/sheets/api/quickstart/nodejs
// Click 'ENABLE THE GOOGLE SHEETS API'
// Download credentials.json
const {google} = require('googleapis');
const sheets_auth = require('./sheets-auth.js');
async function addRow(doc_id, row) {
const auth = await sheets_auth.auth();
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.append({
spreadsheetId: doc_id,
range: 'A1',
valueInputOption: 'RAW',
resource: {
values: [
row
],
},
}, (err, res) => {
console.log(res.statusText);
})
}
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const SCOPES = [
'https://www.googleapis.com/auth/spreadsheets'
];
const TOKEN_PATH = './token.json';
const credentials = JSON.parse(fs.readFileSync('./credentials.json'));
function getCode() {
return new Promise((resolve, reject) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return rl.question('Enter the code from that page here: ', code => {
resolve(code)
rl.close();
})
});
}
function getNewToken(oAuth2Client) {
return new Promise(async (resolve, reject) => {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
let code = await getCode();
oAuth2Client.getToken(code, (err, token) => {
fs.writeFileSync(TOKEN_PATH, JSON.stringify(token))
resolve(token);
});
});
}
async function auth() {
return new Promise(async (resolve, reject) => {
let token;
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
if(!fs.existsSync(TOKEN_PATH)) {
token = await getNewToken(oAuth2Client);
} else {
token = JSON.parse(fs.readFileSync(TOKEN_PATH));
}
oAuth2Client.setCredentials(token);
if(oAuth2Client.isTokenExpiring()) {
await oAuth2Client.refreshAccessToken()
}
resolve(oAuth2Client);
});
}
module.exports = {
auth
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment