node-samples
node-samples copied to clipboard
Use async/await
Expected Behavior
Use async
/await
for all API calls.
https://github.com/google/google-api-nodejs-client#first-example
Actual Behavior
We use callbacks.
Our current policy is to ensure that all sample code is compatible with the oldest LTS release of Node. That is currently v6, which doesn't have support for async/await. That version is scheduled to be end of life in April 2019, at which point we could update our minimum required node version and add this feature.
April 2019, right?
Yes! Just edited my earlier comment.
For those who can't wait till April 2019 :)
import fs from 'fs'
import readline from 'readline'
import { google } from 'googleapis'
import util from 'util'
const SCOPES = [
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.metadata'
]
const TOKEN_PATH = 'token.json'
const CREDENTIALS_PATH = './vault/credentials.json'
const readFile = util.promisify(fs.readFile)
const writeFile = util.promisify(fs.writeFile)
const setup = async () => {
try {
const content = await readFile(CREDENTIALS_PATH)
let oAuth2Client = await authorize(JSON.parse(content))
await listFiles(oAuth2Client)
}
catch (err) {
console.log(err)
}
}
const authorize = async (credentials) => {
const { client_secret, client_id, redirect_uris } = credentials.installed
let oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0])
try {
const token = await readFile(TOKEN_PATH)
oAuth2Client.setCredentials(JSON.parse(token))
console.log('Token already exists')
return oAuth2Client
}
catch (err) {
return await getAccessToken(oAuth2Client)
}
}
const getInput = async (message) => {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
rl.question(message, (data) => {
rl.close()
resolve(data)
})
})
}
const getAccessToken = async (oAuth2Client) => {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
})
console.log('Authorize this app by visiting this url:', authUrl)
let code = await getInput('Enter the code from that page here: ')
try {
let result = await oAuth2Client.getToken(code)
let token = result.tokens
oAuth2Client.setCredentials(token)
try {
await writeFile(TOKEN_PATH, JSON.stringify(token))
console.log('Token stored to', TOKEN_PATH)
return oAuth2Client
}
catch (err) {
console.error(err)
throw err
}
}
catch (err) {
console.error('Error retrieving access token', err)
throw err
}
}
const listFiles = async (auth) => {
const drive = google.drive({ version: 'v3', auth })
try {
const result = await drive.files.list({
pageSize: 10,
fields: 'nextPageToken, files(id, name)'
})
const files = result.data.files
if (files.length) {
console.log('Files:')
files.map((file) => {
console.log(`${file.name} (${file.id})`)
})
} else {
console.log('No files found.')
}
}
catch (err) {
console.log('The API returned an error: ' + err)
}
}
// Main
setup()
@erickoledadevrel Can we revisit this policy? For example, the official Node client uses >= 8 in their samples: https://github.com/googleapis/google-api-nodejs-client/blob/master/samples/package.json#L6
I still prefer compatibility over conciseness. Given that April is only two months away I'd rather just wait until then.
why i insert file , i have a problem server rep:"Request had insufficient authentication scopes."
I'm happy to help once you're ready for async/await
. It'll make most samples much simpler.
I'm happy to help once you're ready for
async/await
. It'll make most samples much simpler.
@fhinkel Did you want to make a PR that resolves this issue?
I can do a PR or code reviews. But consensus was to wait until Node 6 is EOL.
Yup, end of month. Maybe merge a PR to a new branch.