Skip to content

Commit 70a2ec0

Browse files
fix: cleanup and fix samples (googleapis#916)
1 parent dfcae5a commit 70a2ec0

32 files changed

+523
-436
lines changed

package-lock.json

+26
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+6-4
Original file line numberDiff line numberDiff line change
@@ -58,19 +58,20 @@
5858
],
5959
"version": "24.0.0",
6060
"scripts": {
61-
"posttest": "npm run check && npm run lint && npm run license-check",
61+
"posttest": "npm run check && npm run license-check",
6262
"test": "npm run cover",
6363
"doc": "jsdoc -c jsdoc-conf.json",
6464
"prepare": "npm run compile",
6565
"build-tools": "tsc -p tsconfig.tools.json",
6666
"compile": "tsc -p .",
67-
"lint": "semistandard \"samples/**/*.js\"",
67+
"check-samples": "semistandard \"samples/**/*.js\"",
6868
"generate-apis": "npm run build-tools && node build/src/scripts/generate.js && clang-format -i -style='{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}' src/apis/**/*.ts",
6969
"cover": "nyc --cache mocha build/test/ --recursive -t 10000 -S -R spec --require intelli-espower-loader && nyc report --reporter=html",
7070
"pretest": "npm run compile",
7171
"clean": "gts clean",
72-
"check": "gts check",
73-
"fix": "gts fix",
72+
"check": "gts check && npm run check-samples",
73+
"fix": "gts fix && npm run fix-samples",
74+
"fix-samples": "semistandard --fix \"samples/**/*.js\"",
7475
"license-check": "jsgl --local ."
7576
},
7677
"author": "Google Inc.",
@@ -102,6 +103,7 @@
102103
"mkdirp": "0.5.1",
103104
"nock": "9.1.5",
104105
"mocha": "4.1.0",
106+
"nconf": "^0.10.0",
105107
"nunjucks": "^3.0.1",
106108
"nyc": "11.4.1",
107109
"opn": "5.1.0",

samples/README.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
# Samples by API
2+
The following samples show basic usage of various APIs. Throughout these samples, you will find code that relies on various authentication methods.
3+
- **OAuth2** - To use the OAuth2 samples, create a credential in the cloud developer console, and save the file as `oauth2.keys.json` in the samples directory.
4+
- **Service account** - To use the service account based samples, create a new service account in the cloud developer console, and save the file as `jwt.keys.json` in the samples directory.
5+
- **API Key** - To use simple API keys, create a new API Key in the cloud developer console, then store the key in the `api_key` field of `config.json`.
26

3-
The following samples show basic usage of various APIs.
47

58
## ![](http://www.google.com/images/icons/product/analytics-32.png) Google Analytics API
69

samples/analytics/analytics.js

+27-30
Original file line numberDiff line numberDiff line change
@@ -13,55 +13,52 @@
1313

1414
'use strict';
1515

16-
var google = require('../../lib/googleapis.js');
17-
var analytics = google.analytics('v3');
18-
var OAuth2Client = google.auth.OAuth2;
19-
20-
// Client ID and client secret are available at
21-
// https://code.google.com/apis/console
22-
var CLIENT_ID = 'YOUR CLIENT ID HERE';
23-
var CLIENT_SECRET = 'YOUR CLIENT SECRET HERE';
24-
var REDIRECT_URL = 'YOUR REDIRECT URL HERE';
25-
26-
var oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
27-
28-
oauth2Client.setCredentials({
29-
access_token: 'ACCESS TOKEN HERE'
30-
});
16+
const google = require('googleapis');
17+
const analytics = google.analytics('v3');
18+
const sampleClient = require('../sampleclient');
3119

3220
// Custom Goals must be exist prior to used as an objectiveMetric
33-
var objectiveMetric = 'ga:goal1Completions';
21+
const objectiveMetric = 'ga:goal1Completions';
3422

3523
// Serving frameworks listed below:
3624
// https://developers.google.com/analytics/devguides/platform/experiments#serving-framework
37-
var servingFramework = 'API';
25+
const servingFramework = 'API';
3826

3927
// Invalid URLs are used when user is not redirected when showing an experiment
4028
// Read more: http://goo.gl/oVwKH1
41-
var variations = [
29+
const variations = [
4230
{'name': 'Default', 'url': 'http://www.example.com', 'status': 'ACTIVE'},
43-
{'name': 'Variation 1', 'url': 'http://www.1.com', 'status': 'ACTIVE'},
44-
{'name': 'Variation 2', 'url': 'http://www.2.com', 'status': 'ACTIVE'}
31+
{'name': 'variation 1', 'url': 'http://www.1.com', 'status': 'ACTIVE'},
32+
{'name': 'variation 2', 'url': 'http://www.2.com', 'status': 'ACTIVE'}
4533
];
4634

4735
// Specify Experiment configuration
48-
var resourceBody = {
36+
const resourceBody = {
4937
'name': 'Example Experiment',
5038
'status': 'READY_TO_RUN',
5139
'objectiveMetric': objectiveMetric,
5240
'servingFramework': servingFramework,
5341
'variations': variations
5442
};
5543

56-
analytics.management.experiments.insert({
57-
auth: oauth2Client,
58-
accountId: 'your-accountId',
59-
webPropertyId: 'your-webPropertyId',
60-
profileId: 'your-profileId',
61-
resource: resourceBody
62-
}, function (err, body) {
44+
const scopes = [
45+
'https://www.googleapis.com/auth/analytics'
46+
];
47+
48+
sampleClient.authenticate(scopes, (err, authClient) => {
6349
if (err) {
64-
return console.log(err);
50+
throw err;
6551
}
66-
console.log(body);
52+
analytics.management.experiments.insert({
53+
auth: authClient,
54+
accountId: 'your-accountId',
55+
webPropertyId: 'your-webPropertyId',
56+
profileId: 'your-profileId',
57+
resource: resourceBody
58+
}, (err, body) => {
59+
if (err) {
60+
throw err;
61+
}
62+
console.log(body);
63+
});
6764
});

samples/blogger/blogger.js

+11-9
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,20 @@
1313

1414
'use strict';
1515

16-
var google = require('../../lib/googleapis');
17-
var blogger = google.blogger('v3');
18-
var util = require('util');
16+
const google = require('googleapis');
17+
const blogger = google.blogger('v3');
18+
const nconf = require('nconf');
19+
const path = require('path');
20+
21+
// Ex: node blogger.js --api_key "YOUR API KEY"
22+
nconf.argv().env().file(path.join(__dirname, 'config.json'));
1923

2024
blogger.blogs.get({
21-
key: '<YOUR API KEY HERE>',
22-
blogId: '<YOUR BLOG ID HERE>'
23-
}, function (err, result) {
25+
key: nconf.get('api_key'),
26+
blogId: 3213900
27+
}, (err, result) => {
2428
if (err) {
2529
console.error(err);
2630
}
27-
if (result) {
28-
console.log(util.inspect(result));
29-
}
31+
console.log(result);
3032
});

samples/compute/compute.js

+14-10
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@
1313

1414
'use strict';
1515

16-
var request = require('request');
17-
var google = require('../../lib/googleapis.js');
18-
var compute = google.compute('v1');
19-
var uri = 'http://metadata/computeMetadata/v1/project/project-id';
20-
var headers = { 'Metadata-Flavor': 'Google' };
16+
const request = require('request');
17+
const google = require('googleapis');
18+
const compute = google.compute('v1');
19+
const uri = 'http://metadata/computeMetadata/v1/project/project-id';
20+
const headers = { 'Metadata-Flavor': 'Google' };
2121

2222
// This example can be run from a GCE VM in your project. The example fetches
2323
// your project ID from the VM's metadata server, and then uses the Compute API
@@ -26,10 +26,14 @@ var headers = { 'Metadata-Flavor': 'Google' };
2626
// See the defaultauth.js sample for an alternate way of fetching compute credentials.
2727
//
2828
google.options({ auth: new google.auth.Compute() });
29-
request.get({ uri: uri, headers: headers }, function (err, response, project) {
30-
if (!err && response.statusCode === 200) {
31-
compute.zones.list({ project: project }, function (err, result) {
32-
console.log(err, result);
33-
});
29+
request.get({ uri, headers }, (err, res, project) => {
30+
if (err) {
31+
throw err;
3432
}
33+
if (res.statusCode !== 200) {
34+
throw new Error(`Response failed with status ${res.statusCode}`);
35+
}
36+
compute.zones.list({ project }, (err, result) => {
37+
console.log(err, result);
38+
});
3539
});

samples/config.json

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"api_key": "YOUR_API_KEY",
3+
"customsearch_engine_id": "YOUR_CUSTOMSEARCH_ENGINE_ID"
4+
}

samples/customsearch/customsearch.js

+24-10
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,36 @@
1313

1414
'use strict';
1515

16-
var google = require('../../lib/googleapis.js');
17-
var customsearch = google.customsearch('v1');
16+
// Example: node customsearch.js example_term
17+
18+
const google = require('googleapis');
19+
const customsearch = google.customsearch('v1');
20+
const nconf = require('nconf');
21+
const path = require('path');
22+
23+
// Ex: node customsearch.js
24+
// "Google Node.js"
25+
// --api_key "YOUR KEY"
26+
// --customsearch_engine_id="YOUR ID"
27+
nconf.argv().env().file(path.join(__dirname, 'config.json'));
1828

1929
// You can get a custom search engine id at
2030
// https://www.google.com/cse/create/new
21-
const CX = 'INSERT YOUR CUSTOM SEARCH ENGINE ID here';
22-
const API_KEY = 'INSERT YOUR API KEY HERE';
23-
const SEARCH = 'INSERT A GOOGLE REQUEST HERE';
31+
const CX = nconf.get('customsearch_engine_id');
32+
const API_KEY = nconf.get('api_key');
33+
const SEARCH = process.argv[2];
2434

25-
customsearch.cse.list({ cx: CX, q: SEARCH, auth: API_KEY }, function (err, resp) {
35+
customsearch.cse.list({
36+
cx: CX,
37+
q: SEARCH,
38+
auth: API_KEY
39+
}, (err, res) => {
2640
if (err) {
27-
return console.log('An error occured', err);
41+
throw err;
2842
}
2943
// Got the response from custom search
30-
console.log('Result: ' + resp.searchInformation.formattedTotalResults);
31-
if (resp.items && resp.items.length > 0) {
32-
console.log('First result name is ' + resp.items[0].title);
44+
console.log('Result: ' + res.searchInformation.formattedTotalResults);
45+
if (res.items && res.items.length > 0) {
46+
console.log('First result name is ' + res.items[0].title);
3347
}
3448
});

samples/defaultauth.js

+11-7
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313

1414
'use strict';
1515

16-
var google = require('../lib/googleapis.js');
17-
var compute = google.compute('v1');
16+
const google = require('googleapis');
17+
const compute = google.compute('v1');
1818

1919
/**
2020
* The getApplicationDefault method creates the appropriate type of credential client for you,
@@ -34,9 +34,10 @@ var compute = google.compute('v1');
3434
*/
3535

3636
// Get the appropriate type of credential client, depending upon the runtime environment.
37-
google.auth.getApplicationDefault(function (err, authClient) {
37+
google.auth.getApplicationDefault((err, authClient) => {
3838
if (err) {
39-
return console.log('Failed to get the default credentials: ' + String(err));
39+
console.error('Failed to get the default credentials.');
40+
throw err;
4041
}
4142
// The createScopedRequired method returns true when running on GAE or a local developer
4243
// machine. In that case, the desired scopes must be passed in manually. When the code is
@@ -48,8 +49,11 @@ google.auth.getApplicationDefault(function (err, authClient) {
4849
}
4950
// Fetch the list of GCE zones within a project.
5051
// NOTE: You must fill in your valid project ID before running this sample!
51-
var projectId = 'fill in your project id here!';
52-
compute.zones.list({ project: projectId, auth: authClient }, function (err, result) {
53-
console.log(err, result);
52+
const projectId = 'fill in your project id here!';
53+
compute.zones.list({ project: projectId, auth: authClient }, (err, result) => {
54+
if (err) {
55+
throw err;
56+
}
57+
console.log(result);
5458
});
5559
});

samples/directory_v1/group-delete.js

+15-13
Original file line numberDiff line numberDiff line change
@@ -13,36 +13,38 @@
1313

1414
'use strict';
1515

16-
// Dependencies
17-
var googleapis = require('googleapis');
18-
var authData = require('./authData');
16+
const googleapis = require('googleapis');
17+
const nconf = require('nconf');
18+
const path = require('path');
1919

20-
console.log('Auth data is: ', authData);
20+
nconf.argv().env().file(path.join(__dirname, '../jwt.keys.json'));
2121

2222
// Create JWT auth object
23-
var jwt = new googleapis.auth.JWT(
24-
authData.email,
25-
authData.keyFile,
26-
authData.key,
27-
authData.scopes,
28-
authData.subject
23+
const jwt = new googleapis.auth.JWT(
24+
nconf.get('client_email'),
25+
null,
26+
nconf.get('private_key'),
27+
[
28+
'https://www.googleapis.com/auth/admin.directory.group',
29+
'https://www.googleapis.com/auth/admin.directory.group.member'
30+
]
2931
);
3032

3133
// Authorize
32-
jwt.authorize(function (err, data) {
34+
jwt.authorize((err, data) => {
3335
if (err) {
3436
throw err;
3537
}
3638
console.log('You have been successfully authenticated: ', data);
3739

3840
// Get Google Admin API
39-
var admin = googleapis.admin('directory_v1');
41+
const admin = googleapis.admin('directory_v1');
4042

4143
// Delete group
4244
admin.groups.insert({
4345
groupKey: '[email protected]',
4446
auth: jwt
45-
}, function (err, data) {
47+
}, (err, data) => {
4648
console.log(err || data);
4749
});
4850
});

0 commit comments

Comments
 (0)