Skip to content

Commit

Permalink
docs: asyncify the docs and samples (#1097)
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinBeckwith committed Apr 2, 2018
1 parent 9e7f862 commit f124a9f
Show file tree
Hide file tree
Showing 32 changed files with 407 additions and 623 deletions.
72 changes: 22 additions & 50 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -356,28 +356,20 @@ The Google Developers Console provides `.json` file that you can use to configur

``` js
const {google} = require('googleapis');
const drive = google.drive('v2');
const drive = google.drive('v3');

const key = require('/path/to/key.json');
const jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/drive'], // an array of auth scopes
null
);
const jwtClient = new google.auth.JWT({
email: key.client_email,
key: key.private_key,
scopes: ['https://www.googleapis.com/auth/drive']
});

jwtClient.authorize((err, tokens) => {
if (err) {
console.error(err);
throw err;
}
// Make an authorized request to list Drive files.
drive.files.list({
auth: jwtClient
}, (err, response) => {
// handle err and response
});
// Make an authorized request to list Drive files.
drive.files.list({
auth: jwtClient
}, (err, response) => {
// handle err and response
});
```

Expand All @@ -392,40 +384,20 @@ For example, a JWT auth client will be created when your code is running on your
The code below shows how to retrieve a default credential type, depending upon the runtime environment. The createScopedRequired must be called to determine when you need to pass in the scopes manually, and when they have been set for you automatically based on the configured runtime environment.

```js
// This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
// environment variables.
google.auth.getApplicationDefault((err, authClient, projectId) => {
if (err) {
throw err;
}
async function main () {
// This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS environment variables.
const client = await google.auth.getClient();

// The createScopedRequired method returns true when running on GAE or a local developer
// machine. In that case, the desired scopes must be passed in manually. When the code is
// running in GCE or a Managed VM, the scopes are pulled from the GCE metadata server.
// See https://cloud.google.com/compute/docs/authentication for more information.
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
// Scopes can be specified either as an array or as a single, space-delimited string.
authClient = authClient.createScoped([
'https://www.googleapis.com/auth/compute'
]);
}
// Scopes can be specified either as an array or as a single, space-delimited string.
client.scopes = ['https://www.googleapis.com/auth/compute'];

// Fetch the list of GCE zones within a project.
// NOTE: You must fill in your valid project ID before running this sample!
const compute = google.compute({
version: 'v1',
auth: authClient
});
const project = await google.auth.getDefaultProjectId();
const res = await compute.zones.list({ project, auth: client });
console.log(res.data);
}

compute.zones.list({
project: projectId
}, function (err, response) {
if (err) {
throw err;
}
console.log(response.data);
});
});
main().catch(console.error);
```

### Specifying request body
Expand Down Expand Up @@ -549,7 +521,7 @@ const urlshortener = google.urlshortener({
// quotaUser query parameter unless overridden in individual API calls.

// Calls with this drive client will NOT contain the quotaUser query parameter.
const drive = google.drive('v2');
const drive = google.drive('v3');
```

#### Request-level options
Expand Down
28 changes: 11 additions & 17 deletions samples/analytics/analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,27 +45,21 @@ const resourceBody = {
'variations': variations
};

const scopes = [
'https://www.googleapis.com/auth/analytics'
];

function runSample () {
analytics.management.experiments.insert({
async function runSample () {
const res = await analytics.management.experiments.insert({
accountId: 'your-accountId',
webPropertyId: 'your-webPropertyId',
profileId: 'your-profileId',
resource: resourceBody
}, (err, res) => {
if (err) {
throw err;
}
console.log(res.data);
});
console.log(res.data);
return res.data;
}

sampleClient.authenticate(scopes, err => {
if (err) {
throw err;
}
runSample();
});
const scopes = [
'https://www.googleapis.com/auth/analytics'
];

sampleClient.authenticate(scopes)
.then(() => runSample())
.catch(console.error);
9 changes: 3 additions & 6 deletions samples/analyticsReporting/batchGet.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,9 @@ async function runSample () {
// if invoked directly (not tests), authenticate and run the samples
if (module === require.main) {
const scopes = ['https://www.googleapis.com/auth/analytics'];
sampleClient.authenticate(scopes, err => {
if (err) {
throw err;
}
runSample().catch(e => console.error);
});
sampleClient.authenticate(scopes)
.then(c => runSample())
.catch(e => console.error);
}

// export functions for testing purposes
Expand Down
14 changes: 5 additions & 9 deletions samples/customsearch/customsearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,15 @@ const customsearch = google.customsearch('v1');
// "API KEY"
// "CUSTOM ENGINE ID"

function runSample (options, callback) {
async function runSample (options) {
console.log(options);
customsearch.cse.list({
const res = await customsearch.cse.list({
cx: options.cx,
q: options.q,
auth: options.apiKey
}, (err, res) => {
if (err) {
throw err;
}
console.log(res.data);
callback(res.data);
});
console.log(res.data);
return res.data;
}

if (module === require.main) {
Expand All @@ -46,7 +42,7 @@ if (module === require.main) {
apiKey: process.argv[3],
cx: process.argv[4]
};
runSample(options, () => { /* complete */ });
runSample(options).catch(console.error);
}

module.exports = {
Expand Down
38 changes: 13 additions & 25 deletions samples/defaultauth.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ const {google} = require('googleapis');
const compute = google.compute('v1');

/**
* The getApplicationDefault method creates the appropriate type of credential client for you,
* The google.auth.getClient method creates the appropriate type of credential client for you,
* depending upon whether the client is running in Google App Engine, Google Compute Engine, a
* Managed VM, or on a local developer machine. This allows you to write one set of auth code that
* will work in all cases. It most situations, it is advisable to use the getApplicationDefault
* method rather than creating your own JWT or Compute client directly.
* will work in all cases. It most situations, it is advisable to use the getClient method rather
* than creating your own JWT or Compute client directly.
*
* Note: In order to run on a local developer machine, it is necessary to download a private key
* file to your machine, and to set a local environment variable pointing to the location of the
Expand All @@ -34,26 +34,14 @@ const compute = google.compute('v1');
*/

// Get the appropriate type of credential client, depending upon the runtime environment.
google.auth.getApplicationDefault((err, authClient) => {
if (err) {
console.error('Failed to get the default credentials.');
throw err;
}
// The createScopedRequired method returns true when running on GAE or a local developer
// machine. In that case, the desired scopes must be passed in manually. When the code is
// running in GCE or a Managed VM, the scopes are pulled from the GCE metadata server.
// See https://cloud.google.com/compute/docs/authentication for more information.
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
// Scopes can be specified either as an array or as a single, space-delimited string.
authClient = authClient.createScoped(['https://www.googleapis.com/auth/compute']);
}
async function main () {
const client = await google.auth.getClient();
// Scopes can be specified either as an array or as a single, space-delimited string.
client.scopes = ['https://www.googleapis.com/auth/compute'];
// Fetch the list of GCE zones within a project.
// NOTE: You must fill in your valid project ID before running this sample!
const projectId = 'fill in your project id here!';
compute.zones.list({ project: projectId, auth: authClient }, (err, res) => {
if (err) {
throw err;
}
console.log(res.data);
});
});
const project = await google.auth.getDefaultProjectId();
const res = await compute.zones.list({ project, auth: client });
console.log(res.data);
}

main().catch(console.error);
75 changes: 35 additions & 40 deletions samples/drive/download.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,40 +25,42 @@ const drive = google.drive({
auth: sampleClient.oAuth2Client
});

function runSample (fileId, callback) {
const filePath = path.join(os.tmpdir(), uuid.v4());
console.log(`writing to ${filePath}`);
const dest = fs.createWriteStream(filePath);
let progress = 0;
drive.files.get(
{fileId, alt: 'media'},
{responseType: 'stream'},
(err, res) => {
if (err) {
console.error(err);
throw err;
}
res.data
.on('end', () => {
console.log('Done downloading file.');
callback(filePath);
})
.on('error', err => {
console.error('Error downloading file.');
throw err;
})
.on('data', d => {
progress += d.length;
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`Downloaded ${progress} bytes`);
})
.pipe(dest);
});
async function runSample (fileId) {
return new Promise(async (resolve, reject) => {
const filePath = path.join(os.tmpdir(), uuid.v4());
console.log(`writing to ${filePath}`);
const dest = fs.createWriteStream(filePath);
let progress = 0;
const res = await drive.files.get(
{fileId, alt: 'media'},
{responseType: 'stream'}
);
res.data
.on('end', () => {
console.log('Done downloading file.');
resolve(filePath);
})
.on('error', err => {
console.error('Error downloading file.');
reject(err);
})
.on('data', d => {
progress += d.length;
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`Downloaded ${progress} bytes`);
})
.pipe(dest);
});
}

// if invoked directly (not tests), authenticate and run the samples
if (module === require.main) {
if (process.argv.length !== 3) {
console.error('Usage: node samples/drive/download.js $FILE_ID');
process.exit();
}
const fileId = process.argv[2];
const scopes = [
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.appdata',
Expand All @@ -68,16 +70,9 @@ if (module === require.main) {
'https://www.googleapis.com/auth/drive.photos.readonly',
'https://www.googleapis.com/auth/drive.readonly'
];
sampleClient.authenticate(scopes, err => {
if (err) {
throw err;
}
if (process.argv.length !== 3) {
console.error('Usage: node samples/drive/download.js $FILE_ID');
process.exit();
}
runSample(process.argv[2], () => { /* download complete */ });
});
sampleClient.authenticate(scopes)
.then(c => runSample(fileId))
.catch(console.error);
}

// export functions for testing purposes
Expand Down

0 comments on commit f124a9f

Please sign in to comment.