Skip to content

Commit f124a9f

Browse files
docs: asyncify the docs and samples (googleapis#1097)
1 parent 9e7f862 commit f124a9f

32 files changed

+407
-623
lines changed

README.md

+22-50
Original file line numberDiff line numberDiff line change
@@ -356,28 +356,20 @@ The Google Developers Console provides `.json` file that you can use to configur
356356

357357
``` js
358358
const {google} = require('googleapis');
359-
const drive = google.drive('v2');
359+
const drive = google.drive('v3');
360360

361361
const key = require('/path/to/key.json');
362-
const jwtClient = new google.auth.JWT(
363-
key.client_email,
364-
null,
365-
key.private_key,
366-
['https://www.googleapis.com/auth/drive'], // an array of auth scopes
367-
null
368-
);
362+
const jwtClient = new google.auth.JWT({
363+
email: key.client_email,
364+
key: key.private_key,
365+
scopes: ['https://www.googleapis.com/auth/drive']
366+
});
369367

370-
jwtClient.authorize((err, tokens) => {
371-
if (err) {
372-
console.error(err);
373-
throw err;
374-
}
375-
// Make an authorized request to list Drive files.
376-
drive.files.list({
377-
auth: jwtClient
378-
}, (err, response) => {
379-
// handle err and response
380-
});
368+
// Make an authorized request to list Drive files.
369+
drive.files.list({
370+
auth: jwtClient
371+
}, (err, response) => {
372+
// handle err and response
381373
});
382374
```
383375

@@ -392,40 +384,20 @@ For example, a JWT auth client will be created when your code is running on your
392384
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.
393385

394386
```js
395-
// This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
396-
// environment variables.
397-
google.auth.getApplicationDefault((err, authClient, projectId) => {
398-
if (err) {
399-
throw err;
400-
}
387+
async function main () {
388+
// This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS environment variables.
389+
const client = await google.auth.getClient();
401390

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

413394
// Fetch the list of GCE zones within a project.
414-
// NOTE: You must fill in your valid project ID before running this sample!
415-
const compute = google.compute({
416-
version: 'v1',
417-
auth: authClient
418-
});
395+
const project = await google.auth.getDefaultProjectId();
396+
const res = await compute.zones.list({ project, auth: client });
397+
console.log(res.data);
398+
}
419399

420-
compute.zones.list({
421-
project: projectId
422-
}, function (err, response) {
423-
if (err) {
424-
throw err;
425-
}
426-
console.log(response.data);
427-
});
428-
});
400+
main().catch(console.error);
429401
```
430402

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

551523
// Calls with this drive client will NOT contain the quotaUser query parameter.
552-
const drive = google.drive('v2');
524+
const drive = google.drive('v3');
553525
```
554526

555527
#### Request-level options

samples/analytics/analytics.js

+11-17
Original file line numberDiff line numberDiff line change
@@ -45,27 +45,21 @@ const resourceBody = {
4545
'variations': variations
4646
};
4747

48-
const scopes = [
49-
'https://www.googleapis.com/auth/analytics'
50-
];
51-
52-
function runSample () {
53-
analytics.management.experiments.insert({
48+
async function runSample () {
49+
const res = await analytics.management.experiments.insert({
5450
accountId: 'your-accountId',
5551
webPropertyId: 'your-webPropertyId',
5652
profileId: 'your-profileId',
5753
resource: resourceBody
58-
}, (err, res) => {
59-
if (err) {
60-
throw err;
61-
}
62-
console.log(res.data);
6354
});
55+
console.log(res.data);
56+
return res.data;
6457
}
6558

66-
sampleClient.authenticate(scopes, err => {
67-
if (err) {
68-
throw err;
69-
}
70-
runSample();
71-
});
59+
const scopes = [
60+
'https://www.googleapis.com/auth/analytics'
61+
];
62+
63+
sampleClient.authenticate(scopes)
64+
.then(() => runSample())
65+
.catch(console.error);

samples/analyticsReporting/batchGet.js

+3-6
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,9 @@ async function runSample () {
5050
// if invoked directly (not tests), authenticate and run the samples
5151
if (module === require.main) {
5252
const scopes = ['https://www.googleapis.com/auth/analytics'];
53-
sampleClient.authenticate(scopes, err => {
54-
if (err) {
55-
throw err;
56-
}
57-
runSample().catch(e => console.error);
58-
});
53+
sampleClient.authenticate(scopes)
54+
.then(c => runSample())
55+
.catch(e => console.error);
5956
}
6057

6158
// export functions for testing purposes

samples/customsearch/customsearch.js

+5-9
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,15 @@ const customsearch = google.customsearch('v1');
2323
// "API KEY"
2424
// "CUSTOM ENGINE ID"
2525

26-
function runSample (options, callback) {
26+
async function runSample (options) {
2727
console.log(options);
28-
customsearch.cse.list({
28+
const res = await customsearch.cse.list({
2929
cx: options.cx,
3030
q: options.q,
3131
auth: options.apiKey
32-
}, (err, res) => {
33-
if (err) {
34-
throw err;
35-
}
36-
console.log(res.data);
37-
callback(res.data);
3832
});
33+
console.log(res.data);
34+
return res.data;
3935
}
4036

4137
if (module === require.main) {
@@ -46,7 +42,7 @@ if (module === require.main) {
4642
apiKey: process.argv[3],
4743
cx: process.argv[4]
4844
};
49-
runSample(options, () => { /* complete */ });
45+
runSample(options).catch(console.error);
5046
}
5147

5248
module.exports = {

samples/defaultauth.js

+13-25
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ const {google} = require('googleapis');
1717
const compute = google.compute('v1');
1818

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

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

samples/drive/download.js

+35-40
Original file line numberDiff line numberDiff line change
@@ -25,40 +25,42 @@ const drive = google.drive({
2525
auth: sampleClient.oAuth2Client
2626
});
2727

28-
function runSample (fileId, callback) {
29-
const filePath = path.join(os.tmpdir(), uuid.v4());
30-
console.log(`writing to ${filePath}`);
31-
const dest = fs.createWriteStream(filePath);
32-
let progress = 0;
33-
drive.files.get(
34-
{fileId, alt: 'media'},
35-
{responseType: 'stream'},
36-
(err, res) => {
37-
if (err) {
38-
console.error(err);
39-
throw err;
40-
}
41-
res.data
42-
.on('end', () => {
43-
console.log('Done downloading file.');
44-
callback(filePath);
45-
})
46-
.on('error', err => {
47-
console.error('Error downloading file.');
48-
throw err;
49-
})
50-
.on('data', d => {
51-
progress += d.length;
52-
process.stdout.clearLine();
53-
process.stdout.cursorTo(0);
54-
process.stdout.write(`Downloaded ${progress} bytes`);
55-
})
56-
.pipe(dest);
57-
});
28+
async function runSample (fileId) {
29+
return new Promise(async (resolve, reject) => {
30+
const filePath = path.join(os.tmpdir(), uuid.v4());
31+
console.log(`writing to ${filePath}`);
32+
const dest = fs.createWriteStream(filePath);
33+
let progress = 0;
34+
const res = await drive.files.get(
35+
{fileId, alt: 'media'},
36+
{responseType: 'stream'}
37+
);
38+
res.data
39+
.on('end', () => {
40+
console.log('Done downloading file.');
41+
resolve(filePath);
42+
})
43+
.on('error', err => {
44+
console.error('Error downloading file.');
45+
reject(err);
46+
})
47+
.on('data', d => {
48+
progress += d.length;
49+
process.stdout.clearLine();
50+
process.stdout.cursorTo(0);
51+
process.stdout.write(`Downloaded ${progress} bytes`);
52+
})
53+
.pipe(dest);
54+
});
5855
}
5956

6057
// if invoked directly (not tests), authenticate and run the samples
6158
if (module === require.main) {
59+
if (process.argv.length !== 3) {
60+
console.error('Usage: node samples/drive/download.js $FILE_ID');
61+
process.exit();
62+
}
63+
const fileId = process.argv[2];
6264
const scopes = [
6365
'https://www.googleapis.com/auth/drive',
6466
'https://www.googleapis.com/auth/drive.appdata',
@@ -68,16 +70,9 @@ if (module === require.main) {
6870
'https://www.googleapis.com/auth/drive.photos.readonly',
6971
'https://www.googleapis.com/auth/drive.readonly'
7072
];
71-
sampleClient.authenticate(scopes, err => {
72-
if (err) {
73-
throw err;
74-
}
75-
if (process.argv.length !== 3) {
76-
console.error('Usage: node samples/drive/download.js $FILE_ID');
77-
process.exit();
78-
}
79-
runSample(process.argv[2], () => { /* download complete */ });
80-
});
73+
sampleClient.authenticate(scopes)
74+
.then(c => runSample(fileId))
75+
.catch(console.error);
8176
}
8277

8378
// export functions for testing purposes

0 commit comments

Comments
 (0)