node-samples icon indicating copy to clipboard operation
node-samples copied to clipboard

Use async/await

Open grant opened this issue 6 years ago • 11 comments

Expected Behavior

Use async/await for all API calls. https://github.com/google/google-api-nodejs-client#first-example

Actual Behavior

We use callbacks.

grant avatar Aug 22 '18 00:08 grant

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.

erickoledadevrel avatar Aug 22 '18 16:08 erickoledadevrel

April 2019, right?

grant avatar Aug 22 '18 17:08 grant

Yes! Just edited my earlier comment.

erickoledadevrel avatar Aug 22 '18 18:08 erickoledadevrel

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()

hvaoc avatar Nov 27 '18 13:11 hvaoc

@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

grant avatar Feb 07 '19 19:02 grant

I still prefer compatibility over conciseness. Given that April is only two months away I'd rather just wait until then.

erickoledadevrel avatar Feb 11 '19 18:02 erickoledadevrel

why i insert file , i have a problem server rep:"Request had insufficient authentication scopes."

HUYNHVINH2 avatar Mar 08 '19 04:03 HUYNHVINH2

I'm happy to help once you're ready for async/await. It'll make most samples much simpler.

fhinkel avatar Mar 15 '19 16:03 fhinkel

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?

grant avatar Apr 03 '19 07:04 grant

I can do a PR or code reviews. But consensus was to wait until Node 6 is EOL.

fhinkel avatar Apr 03 '19 13:04 fhinkel

Yup, end of month. Maybe merge a PR to a new branch.

grant avatar Apr 03 '19 17:04 grant