Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use async/await #28

Closed
grant opened this issue Aug 22, 2018 · 11 comments
Closed

Use async/await #28

grant opened this issue Aug 22, 2018 · 11 comments

Comments

@grant
Copy link
Contributor

grant commented Aug 22, 2018

Expected Behavior

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

Actual Behavior

We use callbacks.

@erickoledadevrel
Copy link

erickoledadevrel commented Aug 22, 2018

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.

@grant
Copy link
Contributor Author

grant commented Aug 22, 2018

April 2019, right?

@erickoledadevrel
Copy link

Yes! Just edited my earlier comment.

@hvaoc
Copy link

hvaoc commented Nov 27, 2018

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

@grant
Copy link
Contributor Author

grant commented Feb 7, 2019

@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

@erickoledadevrel
Copy link

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

@HUYNHVINH2
Copy link

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

@fhinkel
Copy link

fhinkel commented Mar 15, 2019

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

@grant
Copy link
Contributor Author

grant commented Apr 3, 2019

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?

@fhinkel
Copy link

fhinkel commented Apr 3, 2019

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

@grant
Copy link
Contributor Author

grant commented Apr 3, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants