From d8d45892058f6c06dff8ab8ef7f9660f32d32ffd Mon Sep 17 00:00:00 2001 From: Jason Dobry Date: Mon, 23 May 2016 14:05:15 -0700 Subject: [PATCH] Switched from JSHint to Semistandard and upgraded dependencies. --- .jshintignore | 12 +- appengine/analytics/app.js | 15 +- appengine/bower/server.js | 5 +- appengine/cloudsql/app.js | 21 +- appengine/cloudsql/create_tables.js | 8 +- appengine/datastore/app.js | 21 +- appengine/disk/app.js | 19 +- appengine/endpoints/app.js | 9 +- appengine/errorreporting/app.js | 7 +- appengine/express-memcached-session/server.js | 16 +- appengine/express/app.js | 7 +- appengine/express/routes/index.js | 2 +- appengine/express/routes/users.js | 2 +- appengine/extending-runtime/app.js | 13 +- appengine/grunt/Gruntfile.js | 3 +- appengine/grunt/src/app.js | 7 +- appengine/grunt/src/routes/index.js | 2 +- appengine/grunt/src/routes/users.js | 2 +- appengine/hapi/index.js | 12 +- appengine/hello-world/app.js | 7 +- appengine/koa/app.js | 2 +- appengine/logging/app.js | 7 +- appengine/mailgun/app.js | 28 +- appengine/mailjet/app.js | 18 +- appengine/memcached/app.js | 19 +- appengine/mongodb/server.js | 17 +- appengine/parse-server/server.js | 10 +- appengine/pubsub/app.js | 30 +- appengine/redis/server.js | 18 +- appengine/restify/server.js | 7 +- appengine/sendgrid/app.js | 20 +- appengine/static-files/app.js | 7 +- appengine/storage/app.js | 13 +- appengine/twilio/app.js | 17 +- appengine/webpack/server.js | 19 +- appengine/websockets/app.js | 39 +-- bigquery/dataset_size.js | 41 +-- bigquery/getting_started.js | 23 +- bigquery/load_data_from_csv.js | 21 +- bigquery/load_data_from_gcs.js | 17 +- bigquery/package.json | 7 +- computeengine/package.json | 8 +- computeengine/sendgrid.js | 5 +- computeengine/vms.js | 15 +- computeengine/vms_api.js | 4 +- containerengine/hello-world/server.js | 6 +- datastore/concepts.js | 314 +++++++++--------- datastore/error.js | 11 +- datastore/package.json | 6 +- datastore/tasks.js | 68 ++-- logging/export.js | 21 +- logging/fluent.js | 10 +- logging/list.js | 19 +- logging/package.json | 4 +- logging/write.js | 17 +- monitoring/create_custom_metric.js | 8 +- monitoring/list_resources.js | 8 +- monitoring/package.json | 4 +- package.json | 56 ++-- prediction/hostedmodels.js | 8 +- prediction/package.json | 2 +- pubsub/iam.js | 12 +- pubsub/package.json | 2 +- pubsub/subscription.js | 41 +-- speech/package.json | 4 +- speech/recognize.js | 8 +- storage/authSample.js | 8 +- test/appengine/all.test.js | 24 +- test/bigquery/dataset_size.test.js | 2 +- test/bigquery/getting_started.test.js | 2 +- test/bigquery/load_data_from_csv.test.js | 3 +- test/bigquery/load_data_from_gcs.test.js | 2 - test/computeengine/mailjet.test.js | 4 +- test/computeengine/sendgrid.test.js | 2 +- test/computeengine/vms.test.js | 2 +- test/computeengine/vms_api.test.js | 2 +- test/datastore/concepts.test.js | 8 +- test/datastore/error.test.js | 2 +- test/datastore/tasks.test.js | 2 +- test/datastore/util.js | 8 +- test/functions/log.test.js | 6 +- test/logging/export.test.js | 4 +- test/logging/fluent.test.js | 2 +- test/logging/list.test.js | 8 +- test/monitoring/create_custom_metric.test.js | 12 +- test/monitoring/list_resources.test.js | 6 +- test/prediction/hostedmodels.test.js | 2 +- test/pubsub/iam.test.js | 4 +- test/pubsub/subscription.test.js | 10 +- test/speech/recognize.test.js | 6 +- test/storage/authSample.test.js | 2 +- test/vision/labelDetection.test.js | 2 +- test/vision/landmarkDetection.test.js | 2 +- test/vision/textDetection.test.js | 6 +- vision/faceDetection.js | 20 +- vision/labelDetection.js | 17 +- vision/landmarkDetection.js | 17 +- vision/textDetection.js | 21 +- 98 files changed, 675 insertions(+), 774 deletions(-) diff --git a/.jshintignore b/.jshintignore index 477776a99d2..55ae96a0988 100644 --- a/.jshintignore +++ b/.jshintignore @@ -1,12 +1,4 @@ -appengine/bower/public/bower_components/** -appengine/kraken/public/components/** -appengine/parse-server/cloud/main.js -appengine/sails/config/** -appengine/sails/tasks/** -appengine/sails/assets/** -appengine/sails/api/responses/** -appengine/webpack/dist/** + functions/** -**/node_modules/** -coverage/ + logging/fluent.js \ No newline at end of file diff --git a/appengine/analytics/app.js b/appengine/analytics/app.js index 157d06c1cc9..519e08f1e3d 100644 --- a/appengine/analytics/app.js +++ b/appengine/analytics/app.js @@ -24,7 +24,7 @@ var app = express(); // but will need to be manually set when running locally. See README.md. var GA_TRACKING_ID = process.env.GA_TRACKING_ID; -function trackEvent(category, action, label, value, cb) { +function trackEvent (category, action, label, value, cb) { var data = { v: '1', // API Version. tid: GA_TRACKING_ID, // Tracking ID / Property ID. @@ -35,14 +35,14 @@ function trackEvent(category, action, label, value, cb) { ec: category, // Event category. ea: action, // Event action. el: label, // Event label. - ev: value, // Event value. + ev: value // Event value. }; request.post( 'http://www.google-analytics.com/collect', { form: data }, - function(err, response) { + function (err, response) { if (err) { return cb(err); } if (response.statusCode !== 200) { return cb(new Error('Tracking failed')); @@ -52,13 +52,13 @@ function trackEvent(category, action, label, value, cb) { ); } -app.get('/', function(req, res, next) { +app.get('/', function (req, res, next) { trackEvent( 'Example category', 'Example action', 'Example label', '100', // Event value must be numeric. - function(err) { + function (err) { // This sample treats an event tracking error as a fatal error. Depending // on your application's needs, failing to track an event may not be // considered an error. @@ -68,9 +68,8 @@ app.get('/', function(req, res, next) { }); // Start the server -var server = app.listen(process.env.PORT || 8080, '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/bower/server.js b/appengine/bower/server.js index db3139ceb91..5f4b6e2e9cd 100644 --- a/appengine/bower/server.js +++ b/appengine/bower/server.js @@ -14,15 +14,16 @@ 'use strict'; var express = require('express'); +var path = require('path'); var app = express(); // Setup view engine app.set('view engine', 'jade'); -app.use(express.static(__dirname + '/public')); +app.use(express.static(path.join(__dirname, '/public'))); -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.render('index'); }); diff --git a/appengine/cloudsql/app.js b/appengine/cloudsql/app.js index 337a31c8dab..b1b208204ff 100644 --- a/appengine/cloudsql/app.js +++ b/appengine/cloudsql/app.js @@ -33,7 +33,7 @@ var connection = mysql.createConnection({ database: process.env.MYSQL_DATABASE }); -app.get('/', function(req, res, next) { +app.get('/', function (req, res, next) { var hash = crypto.createHash('sha256'); // Add this visit to the database @@ -43,17 +43,21 @@ app.get('/', function(req, res, next) { userIp: hash.update(req.ip).digest('hex').substr(0, 7) }; - connection.query('INSERT INTO `visits` SET ?', visit, function(err) { - if (err) { return next(err); } + connection.query('INSERT INTO `visits` SET ?', visit, function (err) { + if (err) { + return next(err); + } // Query the last 10 visits from the database. connection.query( 'SELECT `timestamp`, `userIp` FROM `visits` ORDER BY `timestamp` DESC ' + 'LIMIT 10', - function(err, results) { - if (err) { return next(err); } + function (err, results) { + if (err) { + return next(err); + } - var visits = results.map(function(visit) { + var visits = results.map(function (visit) { return format( 'Time: %s, AddrHash: %s', visit.timestamp, @@ -68,9 +72,8 @@ app.get('/', function(req, res, next) { }); }); -var server = app.listen(process.env.PORT || 8080, '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/cloudsql/create_tables.js b/appengine/cloudsql/create_tables.js index 14b34e67686..ec5d33750d5 100644 --- a/appengine/cloudsql/create_tables.js +++ b/appengine/cloudsql/create_tables.js @@ -20,7 +20,7 @@ var prompt = require('prompt'); prompt.start(); -prompt.get(['host', 'user', 'password', 'database'], function(err, config) { +prompt.get(['host', 'user', 'password', 'database'], function (err, config) { if (err) { return; } config.multipleStatements = true; @@ -33,8 +33,10 @@ prompt.get(['host', 'user', 'password', 'database'], function(err, config) { ' `timestamp` DATETIME NULL,' + ' `userIp` VARCHAR(46) NULL,' + ' PRIMARY KEY (`id`));', - function(err) { - if (err) { throw err; } + function (err) { + if (err) { + throw err; + } console.log('Done!'); connection.end(); } diff --git a/appengine/datastore/app.js b/appengine/datastore/app.js index 5e733250eb4..1fd432fcdc6 100644 --- a/appengine/datastore/app.js +++ b/appengine/datastore/app.js @@ -29,7 +29,7 @@ var dataset = gcloud.datastore({ projectId: process.env.GCLOUD_PROJECT }); -app.get('/', function(req, res, next) { +app.get('/', function (req, res, next) { var hash = crypto.createHash('sha256'); // Add this visit to the datastore @@ -40,18 +40,22 @@ app.get('/', function(req, res, next) { // Store a hash of the ip address userIp: hash.update(req.ip).digest('hex').substr(0, 7) } - }, function(err) { - if (err) { return next(err); } + }, function (err) { + if (err) { + return next(err); + } // Query the last 10 visits from the datastore. var query = dataset.createQuery('visit') .order('-timestamp') .limit(10); - dataset.runQuery(query, function(err, entities) { - if (err) { return next(err); } + dataset.runQuery(query, function (err, entities) { + if (err) { + return next(err); + } - var visits = entities.map(function(entity) { + var visits = entities.map(function (entity) { return format( 'Time: %s, AddrHash: %s', entity.data.timestamp, @@ -67,9 +71,8 @@ app.get('/', function(req, res, next) { }); /* Start the server */ -var server = app.listen(process.env.PORT || 8080, '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/disk/app.js b/appengine/disk/app.js index 46dd50787a3..9d8d28bb08f 100644 --- a/appengine/disk/app.js +++ b/appengine/disk/app.js @@ -23,18 +23,22 @@ var crypto = require('crypto'); var app = express(); app.enable('trust proxy'); -app.get('/', function(req, res, next) { +app.get('/', function (req, res, next) { var instanceId = process.env.GAE_MODULE_INSTANCE || '1'; var hash = crypto.createHash('sha256'); // Only store a hash of the ip address var ip = hash.update(req.ip).digest('hex').substr(0, 7); var userIp = util.format('%s\n', ip); - fs.appendFile('/tmp/seen.txt', userIp, function(err) { - if (err) { return next(err); } + fs.appendFile('/tmp/seen.txt', userIp, function (err) { + if (err) { + return next(err); + } - fs.readFile('/tmp/seen.txt', function(err, data) { - if (err) { return next(err); } + fs.readFile('/tmp/seen.txt', function (err, data) { + if (err) { + return next(err); + } res.set('Content-Type', 'text/plain'); res.status(200).send(util.format( @@ -44,9 +48,8 @@ app.get('/', function(req, res, next) { }); }); -var server = app.listen(process.env.PORT || 8080, '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/endpoints/app.js b/appengine/endpoints/app.js index 7001772440d..dea2765b571 100644 --- a/appengine/endpoints/app.js +++ b/appengine/endpoints/app.js @@ -20,11 +20,11 @@ var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json()); -app.post('/echo', function(req, res) { +app.post('/echo', function (req, res) { res.status(200).json({message: req.body.message}); }); -function authInfoHandler(req, res) { +function authInfoHandler (req, res) { var authUser = {id: 'anonymous'}; var encodedInfo = req.get('X-Endpoint-API-UserInfo'); if (encodedInfo) { @@ -37,8 +37,7 @@ app.get('/auth/info/googlejwt', authInfoHandler); app.get('/auth/info/googleidtoken', authInfoHandler); // Start the server -var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || '8080', function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); diff --git a/appengine/errorreporting/app.js b/appengine/errorreporting/app.js index d098f54ce1a..437936e414c 100644 --- a/appengine/errorreporting/app.js +++ b/appengine/errorreporting/app.js @@ -1,4 +1,3 @@ -/*jshint unused:false*/ // Copyright 2015-2016, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,10 +25,10 @@ winston.add(winston.transports.File, { filename: logFile }); -function report(err, req) { +function report (err, req) { var payload = { serviceContext: { - service: 'myapp', + service: 'myapp' }, message: err.stack, context: { @@ -39,7 +38,7 @@ function report(err, req) { referrer: req.header('Referer'), userAgent: req.header('User-Agent'), remoteIp: req.ip, - responseStatusCode: 500, + responseStatusCode: 500 } } }; diff --git a/appengine/express-memcached-session/server.js b/appengine/express-memcached-session/server.js index eff12bc4578..4a653d3f935 100644 --- a/appengine/express-memcached-session/server.js +++ b/appengine/express-memcached-session/server.js @@ -32,14 +32,17 @@ app.use(session({ }) })); -app.get('/', function(req, res){ +app.get('/', function (req, res, next) { publicIp.v4(function (err, ip) { + if (err) { + return next(err); + } var hash = crypto.createHash('sha256'); - // This shows the hashed IP for each + // This shows the hashed IP for each res.write('
' + hash.update(ip).digest('hex').substr(0, 7) + '
'); - if(req.session.views) { + if (req.session.views) { ++req.session.views; } else { req.session.views = 1; @@ -49,9 +52,10 @@ app.get('/', function(req, res){ }); if (module === require.main) { - app.listen(process.env.PORT || 8080, function() { - console.log('Listening on %d', this.address().port); - }); + var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %d', server.address().port); + }); + console.log('Press Ctrl+C to quit.'); } module.exports = app; diff --git a/appengine/express/app.js b/appengine/express/app.js index 9b8ea733184..d363f284fe7 100644 --- a/appengine/express/app.js +++ b/appengine/express/app.js @@ -38,7 +38,7 @@ app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler -app.use(function(req, res, next) { +app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); @@ -49,7 +49,7 @@ app.use(function(req, res, next) { // development error handler // will print stacktrace if (app.get('env') === 'development') { - app.use(function(err, req, res) { + app.use(function (err, req, res) { res.status(err.status || 500); res.render('error', { message: err.message, @@ -60,7 +60,7 @@ if (app.get('env') === 'development') { // production error handler // no stacktraces leaked to user -app.use(function(err, req, res) { +app.use(function (err, req, res) { res.status(err.status || 500); res.render('error', { message: err.message, @@ -68,5 +68,4 @@ app.use(function(err, req, res) { }); }); - module.exports = app; diff --git a/appengine/express/routes/index.js b/appengine/express/routes/index.js index 4e70531535f..907ebced989 100644 --- a/appengine/express/routes/index.js +++ b/appengine/express/routes/index.js @@ -17,7 +17,7 @@ var express = require('express'); var router = express.Router(); // [START hello_world] -router.get('/', function(req, res) { +router.get('/', function (req, res) { res.render('index', { title: 'Hello World! Express.js on Google App Engine.' }); diff --git a/appengine/express/routes/users.js b/appengine/express/routes/users.js index 77ca0721c2d..0d400a494f1 100644 --- a/appengine/express/routes/users.js +++ b/appengine/express/routes/users.js @@ -17,7 +17,7 @@ var express = require('express'); var router = express.Router(); /* GET users listing. */ -router.get('/', function(req, res) { +router.get('/', function (req, res) { res.send('respond with a resource'); }); diff --git a/appengine/extending-runtime/app.js b/appengine/extending-runtime/app.js index bf263878ee3..b74ef64fa91 100644 --- a/appengine/extending-runtime/app.js +++ b/appengine/extending-runtime/app.js @@ -20,20 +20,21 @@ var express = require('express'); var app = express(); -app.get('/', function(req, res, next) { +app.get('/', function (req, res, next) { // Get the output from the "fortune" program. This is installed into the // environment by the Dockerfile. - exec('/usr/games/fortune', function(err, stdout) { - if (err) { return next(err); } + exec('/usr/games/fortune', function (err, stdout) { + if (err) { + return next(err); + } res.set('Content-Type', 'text/plain'); res.status(200).send(stdout); }); }); -var server = app.listen(process.env.PORT || 8080, '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/grunt/Gruntfile.js b/appengine/grunt/Gruntfile.js index ac21775abac..1f4ee6411d3 100644 --- a/appengine/grunt/Gruntfile.js +++ b/appengine/grunt/Gruntfile.js @@ -13,8 +13,7 @@ 'use strict'; -module.exports = function(grunt) { - +module.exports = function (grunt) { grunt.initConfig({ // [START config] jshint: { diff --git a/appengine/grunt/src/app.js b/appengine/grunt/src/app.js index 9b8ea733184..d363f284fe7 100644 --- a/appengine/grunt/src/app.js +++ b/appengine/grunt/src/app.js @@ -38,7 +38,7 @@ app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler -app.use(function(req, res, next) { +app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); @@ -49,7 +49,7 @@ app.use(function(req, res, next) { // development error handler // will print stacktrace if (app.get('env') === 'development') { - app.use(function(err, req, res) { + app.use(function (err, req, res) { res.status(err.status || 500); res.render('error', { message: err.message, @@ -60,7 +60,7 @@ if (app.get('env') === 'development') { // production error handler // no stacktraces leaked to user -app.use(function(err, req, res) { +app.use(function (err, req, res) { res.status(err.status || 500); res.render('error', { message: err.message, @@ -68,5 +68,4 @@ app.use(function(err, req, res) { }); }); - module.exports = app; diff --git a/appengine/grunt/src/routes/index.js b/appengine/grunt/src/routes/index.js index 4bd9407c78e..258dfc6a292 100644 --- a/appengine/grunt/src/routes/index.js +++ b/appengine/grunt/src/routes/index.js @@ -17,7 +17,7 @@ var express = require('express'); var router = express.Router(); // [START hello_world] -router.get('/', function(req, res) { +router.get('/', function (req, res) { res.render('index', { title: 'Hello World! Express.js + Grunt.js on Google App Engine.' }); diff --git a/appengine/grunt/src/routes/users.js b/appengine/grunt/src/routes/users.js index 40172d55152..0b65a3f76dd 100644 --- a/appengine/grunt/src/routes/users.js +++ b/appengine/grunt/src/routes/users.js @@ -17,7 +17,7 @@ var express = require('express'); var router = express.Router(); /* GET users listing. */ -router.get('/', function(req, res, next) { +router.get('/', function (req, res, next) { res.send('respond with a resource'); }); diff --git a/appengine/hapi/index.js b/appengine/hapi/index.js index efeb319d7bc..6f4d712157b 100644 --- a/appengine/hapi/index.js +++ b/appengine/hapi/index.js @@ -18,8 +18,8 @@ var Hapi = require('hapi'); // Create a server with a host and port var server = new Hapi.Server(); -server.connection({ - host: '0.0.0.0', +server.connection({ + host: '0.0.0.0', port: process.env.PORT || 8080 }); // [END server] @@ -27,7 +27,7 @@ server.connection({ // [START index] server.route({ method: 'GET', - path:'/', + path: '/', handler: function (request, reply) { reply('Hello World! Hapi.js on Google App Engine.'); } @@ -37,9 +37,9 @@ server.route({ // Add another route server.route({ method: 'GET', - path:'/hello', + path: '/hello', handler: function (request, reply) { - reply('Hello World! Hapi.js on Google App Engine.'); + reply('Hello World! Hapi.js on Google App Engine.'); } }); @@ -47,4 +47,4 @@ server.route({ server.start(function () { console.log('Server running at:', server.info.uri); }); -// [END server_start] \ No newline at end of file +// [END server_start] diff --git a/appengine/hello-world/app.js b/appengine/hello-world/app.js index 2ecad4fd84f..c4d634324b3 100644 --- a/appengine/hello-world/app.js +++ b/appengine/hello-world/app.js @@ -19,14 +19,13 @@ var express = require('express'); var app = express(); -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.status(200).send('Hello, world!'); }); // Start the server -var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || '8080', function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/koa/app.js b/appengine/koa/app.js index 0ac76394b41..76c2748695e 100644 --- a/appengine/koa/app.js +++ b/appengine/koa/app.js @@ -17,7 +17,7 @@ var koa = require('koa'); var app = koa(); -app.use(function *(){ +app.use(function * () { this.body = 'Hello World! Koa.js on Google App Engine.'; }); diff --git a/appengine/logging/app.js b/appengine/logging/app.js index b3f85ab1082..221876949eb 100644 --- a/appengine/logging/app.js +++ b/appengine/logging/app.js @@ -31,14 +31,13 @@ var logger = new winston.Logger({ ] }); -app.get('/', function(req, res) { +app.get('/', function (req, res) { logger.info('Request from %s', req.ip); res.status(200).send('Logged'); }); -var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || '8080', function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/mailgun/app.js b/appengine/mailgun/app.js index 3e92ee8d78a..3fee4b70fea 100644 --- a/appengine/mailgun/app.js +++ b/appengine/mailgun/app.js @@ -33,13 +33,13 @@ app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // [START index] -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.render('index'); }); // [END index] // [START hello] -app.post('/hello', function(req, res, next) { +app.post('/hello', function (req, res, next) { var servername = ''; var options = {}; @@ -57,27 +57,19 @@ app.post('/hello', function(req, res, next) { function (err) { if (err) { return next(err); - } else { - // Render the index route on success - return res.render('index', { - sent: true - }); } + // Render the index route on success + return res.render('index', { + sent: true + }); } ); }); // [END hello] // [START server] -var server = app.listen( - process.env.PORT || 8080, - '0.0.0.0', - function () { - var address = server.address().address; - var port = server.address().port; - console.log('App listening at http://%s:%s', address, port); - console.log('Press Ctrl+C to quit.'); - } -); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); + console.log('Press Ctrl+C to quit.'); +}); // [END server] - diff --git a/appengine/mailjet/app.js b/appengine/mailjet/app.js index 91b649451a6..1bdfb45e518 100644 --- a/appengine/mailjet/app.js +++ b/appengine/mailjet/app.js @@ -35,13 +35,13 @@ app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // [START index] -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.render('index'); }); // [END index] // [START hello] -app.post('/hello', function(req, res, next) { +app.post('/hello', function (req, res, next) { var options = { // From FromEmail: 'no-reply@appengine-mailjet-demo.com', @@ -72,15 +72,9 @@ app.post('/hello', function(req, res, next) { // [END hello] // [START server] -var server = app.listen( - process.env.PORT || 8080, - '0.0.0.0', - function () { - var address = server.address().address; - var port = server.address().port; - console.log('App listening at http://%s:%s', address, port); - console.log('Press Ctrl+C to quit.'); - } -); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); + console.log('Press Ctrl+C to quit.'); +}); // [END server] diff --git a/appengine/memcached/app.js b/appengine/memcached/app.js index 34dbbf3a765..11b808bb89b 100644 --- a/appengine/memcached/app.js +++ b/appengine/memcached/app.js @@ -27,23 +27,26 @@ var memcachedAddr = process.env.MEMCACHE_PORT_11211_TCP_ADDR || 'localhost'; var memcachedPort = process.env.MEMCACHE_PORT_11211_TCP_PORT || '11211'; var memcached = new Memcached(memcachedAddr + ':' + memcachedPort); -app.get('/', function(req, res, next) { - memcached.get('foo', function(err, value) { - if (err) { return next(err); } +app.get('/', function (req, res, next) { + memcached.get('foo', function (err, value) { + if (err) { + return next(err); + } if (value) { return res.status(200).send('Value: ' + value); } - memcached.set('foo', Math.random(), 60, function(err) { - if (err) { return next(err); } + memcached.set('foo', Math.random(), 60, function (err) { + if (err) { + return next(err); + } return res.redirect('/'); }); }); }); -var server = app.listen(process.env.PORT || 8080, '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/mongodb/server.js b/appengine/mongodb/server.js index 6d4ad1dbd61..39047e987c7 100644 --- a/appengine/mongodb/server.js +++ b/appengine/mongodb/server.js @@ -36,33 +36,32 @@ if (nconf.get('mongoDatabase')) { uri = uri + '/' + nconf.get('mongoDatabase'); } -mongodb.MongoClient.connect(uri, function(err, db) { - +mongodb.MongoClient.connect(uri, function (err, db) { if (err) { throw err; } // Create a simple little server. - http.createServer(function(req, res) { - + http.createServer(function (req, res) { // Track every IP that has visited this site var collection = db.collection('IPs'); - var ip = { address: req.connection.remoteAddress }; - - collection.insert(ip, function(err) { + var ip = { + address: req.connection.remoteAddress + }; + collection.insert(ip, function (err) { if (err) { throw err; } // push out a range var iplist = ''; - collection.find().toArray(function(err, data) { + collection.find().toArray(function (err, data) { if (err) { throw err; } - data.forEach(function(ip) { + data.forEach(function (ip) { iplist += ip.address + '; '; }); diff --git a/appengine/parse-server/server.js b/appengine/parse-server/server.js index db872e560dd..af943705f3a 100644 --- a/appengine/parse-server/server.js +++ b/appengine/parse-server/server.js @@ -18,6 +18,7 @@ var express = require('express'); var nconf = require('nconf'); var ParseServer = require('parse-server').ParseServer; +var path = require('path'); nconf.argv().env().file({ file: 'config.json' }); @@ -25,7 +26,7 @@ var app = express(); var parseServer = new ParseServer({ databaseURI: nconf.get('DATABASE_URI') || 'mongodb://localhost:27017/dev', - cloud: nconf.get('CLOUD_PATH') || __dirname + '/cloud/main.js', + cloud: nconf.get('CLOUD_PATH') || path.join(__dirname, '/cloud/main.js'), appId: nconf.get('APP_ID'), masterKey: nconf.get('MASTER_KEY'), fileKey: nconf.get('FILE_KEY'), @@ -35,13 +36,12 @@ var parseServer = new ParseServer({ // Mount the Parse API server middleware to /parse app.use(process.env.PARSE_MOUNT_PATH || '/parse', parseServer); -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.status(200).send('Hello, world!'); }); -var server = app.listen(process.env.PORT || 8080, '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); diff --git a/appengine/pubsub/app.js b/appengine/pubsub/app.js index 98fab1ca028..7de72d00fae 100644 --- a/appengine/pubsub/app.js +++ b/appengine/pubsub/app.js @@ -39,28 +39,29 @@ var pubsub = gcloud.pubsub({ var topic = pubsub.topic(process.env.PUBSUB_TOPIC); // [START index] -app.get('/', function(req, res) { - res.render('index', {messages: messages}); +app.get('/', function (req, res) { + res.render('index', { messages: messages }); }); -app.post('/', formBodyParser, function(req, res, next) { - if(!req.body.payload) { +app.post('/', formBodyParser, function (req, res, next) { + if (!req.body.payload) { return res.status(400).send('Missing payload'); } topic.publish({ - data: req.body.payload - }, - function(err){ - if(err) { return next(err); } - res.status(200).send('Message sent'); - }); + data: req.body.payload + }, function (err) { + if (err) { + return next(err); + } + res.status(200).send('Message sent'); + }); }); // [END index] // [START push] -app.post('/pubsub/push', jsonBodyParser, function(req, res) { - if(req.query.token !== PUBSUB_VERIFICATION_TOKEN) { +app.post('/pubsub/push', jsonBodyParser, function (req, res) { + if (req.query.token !== PUBSUB_VERIFICATION_TOKEN) { return res.status(400).send(); } @@ -74,9 +75,8 @@ app.post('/pubsub/push', jsonBodyParser, function(req, res) { // [END push] // Start the server -var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || '8080', function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/redis/server.js b/appengine/redis/server.js index ecd41c0dcb7..7a070868c53 100644 --- a/appengine/redis/server.js +++ b/appengine/redis/server.js @@ -17,17 +17,17 @@ var redis = require('redis'); var http = require('http'); var nconf = require('nconf'); -// read in keys and secrets. You can store these in a variety of ways. -// I like to use a keys.json file that is in the .gitignore file, +// read in keys and secrets. You can store these in a variety of ways. +// I like to use a keys.json file that is in the .gitignore file, // but you can also store them in environment variables nconf.argv().env().file('keys.json'); // [START client] -// Connect to a redis server provisioned over at -// Redis Labs. See the README for more info. +// Connect to a redis server provisioned over at +// Redis Labs. See the README for more info. var client = redis.createClient( nconf.get('redisPort') || '6379', - nconf.get('redisHost') || '127.0.0.1', + nconf.get('redisHost') || '127.0.0.1', { 'auth_pass': nconf.get('redisKey'), 'return_buffers': true @@ -37,7 +37,7 @@ var client = redis.createClient( }); // [END client] -// Create a simple little server. +// Create a simple little server. http.createServer(function (req, res) { client.on('error', function (err) { console.log('Error ' + err); @@ -48,7 +48,7 @@ http.createServer(function (req, res) { client.lpush(listName, req.connection.remoteAddress); client.ltrim(listName, 0, 25); - // push out a range + // push out a range var iplist = ''; client.lrange(listName, 0, -1, function (err, data) { if (err) { @@ -59,10 +59,10 @@ http.createServer(function (req, res) { console.log('IP: ' + ip + '\n'); iplist += ip + '; '; }); - + res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(iplist); }); }).listen(process.env.PORT || 8080); -console.log('started web process'); \ No newline at end of file +console.log('started web process'); diff --git a/appengine/restify/server.js b/appengine/restify/server.js index a7c3821695f..8000ee08e85 100644 --- a/appengine/restify/server.js +++ b/appengine/restify/server.js @@ -14,6 +14,7 @@ 'use strict'; // [START server] +var PORT = process.env.PORT || 8080; var restify = require('restify'); var server = restify.createServer({ @@ -38,7 +39,7 @@ server.get('/', function (req, res) { // [END index] // [START server_start] -server.listen(process.env.PORT || 8080, function () { - console.log('%s listening at %s', server.name, server.url); +server.listen(PORT, function () { + console.log('App listening on port %s', PORT); }); -// [END server_start] \ No newline at end of file +// [END server_start] diff --git a/appengine/sendgrid/app.js b/appengine/sendgrid/app.js index 127f5f95654..728eee0c21e 100644 --- a/appengine/sendgrid/app.js +++ b/appengine/sendgrid/app.js @@ -36,18 +36,18 @@ app.set('view engine', 'jade'); app.use(bodyParser.urlencoded({ extended: false })); // [START index] -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.render('index'); }); // [END index] // [START hello] -app.post('/hello', function(req, res, next) { +app.post('/hello', function (req, res, next) { Sendgrid.send({ from: SENDGRID_SENDER, // From address to: req.body.email, // To address subject: 'Hello World!', // Subject - text: 'Sendgrid on Google App Engine with Node.js', // Content + text: 'Sendgrid on Google App Engine with Node.js' // Content }, function (err) { if (err) { return next(err); @@ -62,16 +62,10 @@ app.post('/hello', function(req, res, next) { if (module === require.main) { // [START server] - var server = app.listen( - process.env.PORT || 8080, - '0.0.0.0', - function () { - var address = server.address().address; - var port = server.address().port; - console.log('App listening at http://%s:%s', address, port); - console.log('Press Ctrl+C to quit.'); - } - ); + var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); + console.log('Press Ctrl+C to quit.'); + }); // [END server] } diff --git a/appengine/static-files/app.js b/appengine/static-files/app.js index 38f29b399ae..806b4849a9b 100644 --- a/appengine/static-files/app.js +++ b/appengine/static-files/app.js @@ -23,14 +23,13 @@ app.set('view engine', 'jade'); // Use the built-in express middleware for serving static files from './public' app.use('/static', express.static('public')); -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.render('index'); }); // Start the server -var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || '8080', function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/storage/app.js b/appengine/storage/app.js index 70ee32f0b7a..7f8d8f2bb8d 100644 --- a/appengine/storage/app.js +++ b/appengine/storage/app.js @@ -43,14 +43,14 @@ var bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET); // [START form] // Display a form for uploading files. -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.render('form.jade'); }); // [END form] // [START process] // Process the file upload and upload to Google Cloud Storage. -app.post('/upload', multer.single('file'), function(req, res, next) { +app.post('/upload', multer.single('file'), function (req, res, next) { if (!req.file) { return res.status(400).send('No file uploaded.'); } @@ -59,11 +59,11 @@ app.post('/upload', multer.single('file'), function(req, res, next) { var blob = bucket.file(req.file.originalname); var blobStream = blob.createWriteStream(); - blobStream.on('error', function(err) { + blobStream.on('error', function (err) { return next(err); }); - blobStream.on('finish', function() { + blobStream.on('finish', function () { // The public URL can be used to directly access the file via HTTP. var publicUrl = format( 'https://storage.googleapis.com/%s/%s', @@ -75,9 +75,8 @@ app.post('/upload', multer.single('file'), function(req, res, next) { }); // [END process] -var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || '8080', function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/twilio/app.js b/appengine/twilio/app.js index a3a8cd0a1d8..36772c93be1 100644 --- a/appengine/twilio/app.js +++ b/appengine/twilio/app.js @@ -39,7 +39,7 @@ var TwimlResponse = require('twilio').TwimlResponse; // [END config] // [START receive_call] -app.post('/call/receive', function(req, res) { +app.post('/call/receive', function (req, res) { var resp = new TwimlResponse(); resp.say('Hello from Google App Engine.'); @@ -50,7 +50,7 @@ app.post('/call/receive', function(req, res) { // [END receive_call] // [START send_sms] -app.get('/sms/send', function(req, res, next) { +app.get('/sms/send', function (req, res, next) { var to = req.query.to; if (!to) { return res.status(400).send( @@ -61,15 +61,17 @@ app.get('/sms/send', function(req, res, next) { to: to, from: TWILIO_NUMBER, body: 'Hello from Google App Engine' - }, function(err) { - if (err) { return next(err); } + }, function (err) { + if (err) { + return next(err); + } res.status(200).send('Message sent.'); }); }); // [END send_sms] // [START receive_sms] -app.post('/sms/receive', bodyParser, function(req, res) { +app.post('/sms/receive', bodyParser, function (req, res) { var sender = req.body.From; var body = req.body.Body; @@ -83,9 +85,8 @@ app.post('/sms/receive', bodyParser, function(req, res) { // [END receive_sms] // Start the server -var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); +var server = app.listen(process.env.PORT || '8080', function () { + console.log('App listening on port %s', server.address().port); console.log('Press Ctrl+C to quit.'); }); // [END app] diff --git a/appengine/webpack/server.js b/appengine/webpack/server.js index 13f90ea6688..28f917304db 100644 --- a/appengine/webpack/server.js +++ b/appengine/webpack/server.js @@ -14,25 +14,20 @@ 'use strict'; var express = require('express'); +var path = require('path'); var app = express(); // Setup view engine app.set('view engine', 'jade'); -app.use(express.static(__dirname + '/dist')); +app.use(express.static(path.resolve(path.join(__dirname, '/dist')))); -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.render('index'); }); -var server = app.listen( - process.env.PORT || 8080, - '0.0.0.0', - function () { - var address = server.address().address; - var port = server.address().port; - console.log('App listening at http://%s:%s', address, port); - console.log('Press Ctrl+C to quit.'); - } -); +var server = app.listen(process.env.PORT || 8080, function () { + console.log('App listening on port %s', server.address().port); + console.log('Press Ctrl+C to quit.'); +}); diff --git a/appengine/websockets/app.js b/appengine/websockets/app.js index 8fdc0d041c5..377b4beb5d4 100644 --- a/appengine/websockets/app.js +++ b/appengine/websockets/app.js @@ -26,14 +26,14 @@ app.set('view engine', 'jade'); require('express-ws')(app); // A simple echo service. -app.ws('/echo', function(ws) { - ws.on('message', function(msg) { +app.ws('/echo', function (ws) { + ws.on('message', function (msg) { ws.send(msg); }); }); -app.get('/', function(req, res) { - getExternalIp(function(externalIp){ +app.get('/', function (req, res) { + getExternalIp(function (externalIp) { res.render('index.jade', {externalIp: externalIp}); }); }); @@ -45,7 +45,7 @@ app.get('/', function(req, res) { var METADATA_NETWORK_INTERFACE_URL = 'http://metadata/computeMetadata/v1/' + '/instance/network-interfaces/0/access-configs/0/external-ip'; -function getExternalIp(cb) { +function getExternalIp (cb) { var options = { url: METADATA_NETWORK_INTERFACE_URL, headers: { @@ -53,8 +53,8 @@ function getExternalIp(cb) { } }; - request(options, function(err, resp, body){ - if(err || resp.statusCode !== 200) { + request(options, function (err, resp, body) { + if (err || resp.statusCode !== 200) { console.log('Error while talking to metadata server, assuming localhost'); return cb('localhost'); } @@ -64,26 +64,15 @@ function getExternalIp(cb) { // [END external_ip] // Start the websocket server -var wsServer = app.listen( - '65080', - '0.0.0.0', - function() { - console.log('Websocket server listening at http://%s:%s', - wsServer.address().address, - wsServer.address().port); - } -); +var wsServer = app.listen('65080', function () { + console.log('Websocket server listening on port %s', wsServer.address().port); +}); // Additionally listen for non-websocket connections on the default App Engine // port 8080. Using http.createServer will skip express-ws's logic to upgrade // websocket connections. -var server = http.createServer(app).listen( - process.env.PORT || '8080', - '0.0.0.0', - function() { - console.log('App listening at http://%s:%s', server.address().address, - server.address().port); - console.log('Press Ctrl+C to quit.'); - } -); +var server = http.createServer(app).listen(process.env.PORT || '8080', function () { + console.log('App listening on port %s', server.address().port); + console.log('Press Ctrl+C to quit.'); +}); // [END app] diff --git a/bigquery/dataset_size.js b/bigquery/dataset_size.js index 96c8580acd6..ef674cc8572 100644 --- a/bigquery/dataset_size.js +++ b/bigquery/dataset_size.js @@ -16,22 +16,13 @@ var async = require('async'); // [START auth] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); - -// Get a reference to the bigquery component -var bigquery = gcloud.bigquery(); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // [END auth] -// not going to use this bigquery instance -bigquery = undefined; - // [START list_tables] /** * Retrieve all tables for the specified dataset. @@ -41,7 +32,7 @@ bigquery = undefined; * @param {string} [pageToken] Page to retrieve. * @param {Function} callback Callback function. */ -function getAllTablesExample(bigquery, datasetId, pageToken, callback) { +function getAllTablesExample (bigquery, datasetId, pageToken, callback) { if (typeof pageToken === 'function') { callback = pageToken; pageToken = undefined; @@ -63,6 +54,7 @@ function getAllTablesExample(bigquery, datasetId, pageToken, callback) { if (nextQuery) { // Grab the remaining pages of tables recursively return getAllTablesExample( + bigquery, datasetId, nextQuery.token, function (err, _tables) { @@ -87,21 +79,20 @@ function getAllTablesExample(bigquery, datasetId, pageToken, callback) { * @param {string} datasetId The dataset, e.g. "hacker_news" * @param {Function} callback Callback function. */ -function getSizeExample(projectId, datasetId, callback) { - if (!projectId) { - return callback(new Error('projectId is required!')); - } +function getSizeExample (projectId, datasetId, callback) { if (!datasetId) { return callback(new Error('datasetId is require!')); } - var gcloud = require('gcloud')({ - projectId: projectId || process.env.GCLOUD_PROJECT + var bigquery = gcloud.bigquery({ + projectId: projectId }); - var bigquery = gcloud.bigquery(); // Fetch all tables in the dataset getAllTablesExample(bigquery, datasetId, function (err, tables) { + if (err) { + return callback(err); + } return async.parallel(tables.map(function (table) { return function (cb) { // Fetch more detailed info for each table @@ -151,9 +142,5 @@ if (module === require.main) { if (args.length !== 2) { throw new Error('Usage: node dataset_size.js '); } - exports.main( - args[0], - args[1], - console.log - ); + exports.main(args[0], args[1], console.log); } diff --git a/bigquery/getting_started.js b/bigquery/getting_started.js index 45eddeca352..aeee607c3b1 100644 --- a/bigquery/getting_started.js +++ b/bigquery/getting_started.js @@ -15,21 +15,18 @@ 'use strict'; // [START auth] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // Get a reference to the bigquery component var bigquery = gcloud.bigquery(); // [END auth] // [START print] -function printExample(rows) { +function printExample (rows) { console.log('Query Results:'); rows.forEach(function (row) { var str = ''; @@ -50,11 +47,11 @@ function printExample(rows) { * * @param {Function} callback Callback function. */ -function queryExample(callback) { +function queryExample (callback) { var query = 'SELECT TOP(corpus, 10) as title, COUNT(*) as unique_words\n' + 'FROM [publicdata:samples.shakespeare];'; - bigquery.query(query, function(err, rows) { + bigquery.query(query, function (err, rows) { if (err) { return callback(err); } @@ -73,7 +70,5 @@ exports.main = function (cb) { }; if (module === require.main) { - exports.main( - console.log - ); + exports.main(console.log); } diff --git a/bigquery/load_data_from_csv.js b/bigquery/load_data_from_csv.js index 9e78115e5da..bed894e306e 100644 --- a/bigquery/load_data_from_csv.js +++ b/bigquery/load_data_from_csv.js @@ -15,15 +15,13 @@ 'use strict'; var fs = require('fs'); +var path = require('path'); -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // Get a reference to the bigquery component var bigquery = gcloud.bigquery(); @@ -35,7 +33,7 @@ var bigquery = gcloud.bigquery(); * @param {number} timeout Maximum time to wait (milliseconds). * @param {Function} Callback function. */ -function pollJobUntilDone(job, timeout, timeWaited, callback) { +function pollJobUntilDone (job, timeout, timeWaited, callback) { job.getMetadata(function (err, metadata) { if (err) { return callback(err); @@ -63,8 +61,7 @@ function pollJobUntilDone(job, timeout, timeWaited, callback) { * @param {string} tableName The table. * @param {Function} callback Callback function. */ -function loadDataFromCsvExample(pathToCsvFile, datasetId, tableName, callback) { - +function loadDataFromCsvExample (pathToCsvFile, datasetId, tableName, callback) { if (!pathToCsvFile || typeof pathToCsvFile !== 'string') { return callback(new Error('pathToCsvFile is required!')); } @@ -99,7 +96,7 @@ function loadDataFromCsvExample(pathToCsvFile, datasetId, tableName, callback) { exports.createTable = function (datasetId, tableName, callback) { var dataset = bigquery.dataset(datasetId); - var pathToSchemaFile = __dirname + '/resources/schema.json'; + var pathToSchemaFile = path.join(__dirname, '/resources/schema.json'); fs.readFile(pathToSchemaFile, { encoding: 'utf8' }, function (err, file) { if (err) { return callback(err); diff --git a/bigquery/load_data_from_gcs.js b/bigquery/load_data_from_gcs.js index f620a0472a9..4c8dce9d10d 100644 --- a/bigquery/load_data_from_gcs.js +++ b/bigquery/load_data_from_gcs.js @@ -16,14 +16,11 @@ var request = require('request'); -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // Get a reference to the bigquery component var bigquery = gcloud.bigquery(); @@ -35,7 +32,7 @@ var bigquery = gcloud.bigquery(); * @param {number} timeout Maximum time to wait (milliseconds). * @param {Function} Callback function. */ -function pollJobUntilDone(job, timeout, timeWaited, callback) { +function pollJobUntilDone (job, timeout, timeWaited, callback) { job.getMetadata(function (err, metadata) { if (err) { return callback(err); @@ -64,7 +61,7 @@ function pollJobUntilDone(job, timeout, timeWaited, callback) { * @param {string} tableName The table. * @param {Function} callback Callback function. */ -function loadDataFromCsvExample(bucket, file, datasetId, tableName, callback) { +function loadDataFromCsvExample (bucket, file, datasetId, tableName, callback) { if (!bucket || typeof bucket !== 'string') { throw new Error('bucket is required!'); } diff --git a/bigquery/package.json b/bigquery/package.json index de7c37f9f2d..9f9568b8b17 100644 --- a/bigquery/package.json +++ b/bigquery/package.json @@ -8,12 +8,9 @@ "engines": { "node": ">=0.10.x" }, - "scripts": { - "dataset_size": "node dataset_size.js" - }, "dependencies": { "async": "^1.5.2", - "gcloud": "^0.30.3", - "request": "^2.69.0" + "gcloud": "^0.34.0", + "request": "^2.72.0" } } diff --git a/computeengine/package.json b/computeengine/package.json index ac9dfa63837..c812b22ecc4 100644 --- a/computeengine/package.json +++ b/computeengine/package.json @@ -15,10 +15,10 @@ "vms_api": "node vms_api.js" }, "dependencies": { - "gcloud": "^0.30.3", - "googleapis": "^4.0.0", - "nodemailer": "^2.3.2", - "nodemailer-smtp-transport": "^2.4.2", + "gcloud": "^0.34.0", + "googleapis": "^7.1.0", + "nodemailer": "^2.4.1", + "nodemailer-smtp-transport": "^2.5.0", "sendgrid": "^2.0.0" } } diff --git a/computeengine/sendgrid.js b/computeengine/sendgrid.js index b2c45df6fac..9f4c07812d6 100644 --- a/computeengine/sendgrid.js +++ b/computeengine/sendgrid.js @@ -25,9 +25,8 @@ Sendgrid.send({ text: 'Hello!\n\nThis a test email from Node.js.' // Content }, function (err, json) { if (err) { - console.log(err); - } else { - console.log(json); + return console.log(err); } + console.log(json); }); // [END send] diff --git a/computeengine/vms.js b/computeengine/vms.js index e891e0861e1..e648ed10212 100644 --- a/computeengine/vms.js +++ b/computeengine/vms.js @@ -15,14 +15,11 @@ 'use strict'; // [START auth] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // [END auth] // [START initialize] @@ -34,7 +31,7 @@ var compute = gcloud.compute(); /** * @param {Function} callback Callback function. */ -function getVmsExample(callback) { +function getVmsExample (callback) { // In this example we only want one VM per page var options = { maxResults: 1 diff --git a/computeengine/vms_api.js b/computeengine/vms_api.js index c39bbeb2092..9e3e5ff0836 100644 --- a/computeengine/vms_api.js +++ b/computeengine/vms_api.js @@ -20,7 +20,7 @@ var compute = google.compute('v1'); // [END initialize] // [START auth] -function auth(callback) { +function auth (callback) { google.auth.getApplicationDefault(function (err, authClient) { if (err) { return callback(err); @@ -50,7 +50,7 @@ function auth(callback) { /** * @param {Function} callback Callback function. */ -function getVmsExample(callback) { +function getVmsExample (callback) { auth(function (err, authClient) { if (err) { return callback(err); diff --git a/containerengine/hello-world/server.js b/containerengine/hello-world/server.js index c2a91c87abf..b07b75f691f 100644 --- a/containerengine/hello-world/server.js +++ b/containerengine/hello-world/server.js @@ -15,9 +15,9 @@ // [START all] var http = require('http'); -var handleRequest = function(request, response) { - response.writeHead(200); - response.end('Hello Kubernetes!'); +var handleRequest = function (req, res) { + res.writeHead(200); + res.end('Hello Kubernetes!'); }; var www = http.createServer(handleRequest); www.listen(process.env.PORT || 8080); diff --git a/datastore/concepts.js b/datastore/concepts.js index 6ca55280cc6..47304e88c70 100644 --- a/datastore/concepts.js +++ b/datastore/concepts.js @@ -14,6 +14,10 @@ 'use strict'; var asyncUtil = require('async'); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication var gcloud = require('gcloud'); module.exports = { @@ -26,27 +30,21 @@ module.exports = { // This mock is used in the documentation snippets. var datastore = { - delete: function() {}, - get: function() {}, - insert: function() {}, - key: function() {}, - update: function() {}, - upsert: function() {}, - runQuery: function() {}, - save: function() {} + delete: function () {}, + get: function () {}, + insert: function () {}, + key: function () {}, + update: function () {}, + upsert: function () {}, + runQuery: function () {}, + save: function () {} }; -var keyFile = process.env.DATASTORE_KEYFILE || - process.env.GOOGLE_APPLICATION_CREDENTIALS; - -function Entity(projectId) { +function Entity (projectId) { var options = { projectId: projectId }; - if (keyFile) { - options.keyFilename = keyFile; - } this.datastore = gcloud.datastore(options); // To create the keys, we have to use this instance of Datastore. @@ -58,7 +56,7 @@ function Entity(projectId) { this.keyWithMultiLevelParent = this.getKeyWithMultiLevelParent(); } -Entity.prototype.getIncompleteKey = function() { +Entity.prototype.getIncompleteKey = function () { // [START incomplete_key] var taskKey = datastore.key('Task'); // [END incomplete_key] @@ -66,7 +64,7 @@ Entity.prototype.getIncompleteKey = function() { return taskKey; }; -Entity.prototype.getNamedKey = function() { +Entity.prototype.getNamedKey = function () { // [START named_key] var taskKey = datastore.key([ 'Task', @@ -77,7 +75,7 @@ Entity.prototype.getNamedKey = function() { return taskKey; }; -Entity.prototype.getKeyWithParent = function() { +Entity.prototype.getKeyWithParent = function () { // [START key_with_parent] var taskKey = datastore.key([ 'TaskList', @@ -90,7 +88,7 @@ Entity.prototype.getKeyWithParent = function() { return taskKey; }; -Entity.prototype.getKeyWithMultiLevelParent = function() { +Entity.prototype.getKeyWithMultiLevelParent = function () { // [START key_with_multilevel_parent] var taskKey = datastore.key([ 'User', @@ -105,7 +103,7 @@ Entity.prototype.getKeyWithMultiLevelParent = function() { return taskKey; }; -Entity.prototype.getTask = function() { +Entity.prototype.getTask = function () { // [START basic_entity] var task = { type: 'Personal', @@ -118,35 +116,35 @@ Entity.prototype.getTask = function() { return task; }; -Entity.prototype.testIncompleteKey = function(callback) { +Entity.prototype.testIncompleteKey = function (callback) { this.datastore.save({ key: this.incompleteKey, data: {} }, callback); }; -Entity.prototype.testNamedKey = function(callback) { +Entity.prototype.testNamedKey = function (callback) { this.datastore.save({ key: this.namedKey, data: {} }, callback); }; -Entity.prototype.testKeyWithParent = function(callback) { +Entity.prototype.testKeyWithParent = function (callback) { this.datastore.save({ key: this.keyWithParent, data: {} }, callback); }; -Entity.prototype.testKeyWithMultiLevelParent = function(callback) { +Entity.prototype.testKeyWithMultiLevelParent = function (callback) { this.datastore.save({ key: this.keyWithMultiLevelParent, data: {} }, callback); }; -Entity.prototype.testEntityWithParent = function(callback) { +Entity.prototype.testEntityWithParent = function (callback) { var taskKey = this.keyWithParent; // [START entity_with_parent] @@ -164,7 +162,7 @@ Entity.prototype.testEntityWithParent = function(callback) { this.datastore.save(task, callback); }; -Entity.prototype.testProperties = function(callback) { +Entity.prototype.testProperties = function (callback) { // jshint camelcase:false // [START properties] var task = { @@ -183,7 +181,7 @@ Entity.prototype.testProperties = function(callback) { }, callback); }; -Entity.prototype.testArrayValue = function(callback) { +Entity.prototype.testArrayValue = function (callback) { // [START array_value] var task = { tags: [ @@ -203,14 +201,14 @@ Entity.prototype.testArrayValue = function(callback) { }, callback); }; -Entity.prototype.testBasicEntity = function(callback) { +Entity.prototype.testBasicEntity = function (callback) { this.datastore.save({ key: this.getIncompleteKey(), data: this.getTask() }, callback); }; -Entity.prototype.testUpsert = function(callback) { +Entity.prototype.testUpsert = function (callback) { var taskKey = this.getIncompleteKey(); var task = this.getTask(); @@ -218,7 +216,7 @@ Entity.prototype.testUpsert = function(callback) { datastore.upsert({ key: taskKey, data: task - }, function(err) { + }, function (err) { if (!err) { // Task inserted successfully. } @@ -231,7 +229,7 @@ Entity.prototype.testUpsert = function(callback) { }, callback); }; -Entity.prototype.testInsert = function(callback) { +Entity.prototype.testInsert = function (callback) { var taskKey = this.getIncompleteKey(); var task = this.getTask(); @@ -239,7 +237,7 @@ Entity.prototype.testInsert = function(callback) { datastore.insert({ key: taskKey, data: task - }, function(err) { + }, function (err) { if (!err) { // Task inserted successfully. } @@ -253,13 +251,13 @@ Entity.prototype.testInsert = function(callback) { }, callback); }; -Entity.prototype.testLookup = function(callback) { +Entity.prototype.testLookup = function (callback) { var self = this; var taskKey = this.getIncompleteKey(); // jshint unused:false // [START lookup] - datastore.get(taskKey, function(err, entity) { + datastore.get(taskKey, function (err, entity) { if (!err) { // Task found. @@ -277,7 +275,7 @@ Entity.prototype.testLookup = function(callback) { method: 'insert', key: taskKey, data: {} - }, function(err) { + }, function (err) { if (err) { callback(err); return; @@ -287,7 +285,7 @@ Entity.prototype.testLookup = function(callback) { }); }; -Entity.prototype.testUpdate = function(callback) { +Entity.prototype.testUpdate = function (callback) { var self = this; var taskKey = this.getIncompleteKey(); var task = this.getTask(); @@ -296,7 +294,7 @@ Entity.prototype.testUpdate = function(callback) { datastore.update({ key: taskKey, data: task - }, function(err) { + }, function (err) { if (!err) { // Task updated successfully. } @@ -307,7 +305,7 @@ Entity.prototype.testUpdate = function(callback) { method: 'insert', key: taskKey, data: {} - }, function(err) { + }, function (err) { if (err) { callback(err); return; @@ -320,12 +318,12 @@ Entity.prototype.testUpdate = function(callback) { }); }; -Entity.prototype.testDelete = function(callback) { +Entity.prototype.testDelete = function (callback) { var self = this; var taskKey = this.getIncompleteKey(); // [START delete] - datastore.delete(taskKey, function(err) { + datastore.delete(taskKey, function (err) { if (!err) { // Task deleted successfully. } @@ -336,7 +334,7 @@ Entity.prototype.testDelete = function(callback) { method: 'insert', key: taskKey, data: {} - }, function(err) { + }, function (err) { if (err) { callback(err); return; @@ -346,7 +344,7 @@ Entity.prototype.testDelete = function(callback) { }); }; -Entity.prototype.testBatchUpsert = function(callback) { +Entity.prototype.testBatchUpsert = function (callback) { var taskKey1 = this.datastore.key(['Task', 1]); var taskKey2 = this.datastore.key(['Task', 2]); @@ -374,7 +372,7 @@ Entity.prototype.testBatchUpsert = function(callback) { key: taskKey2, data: task2 } - ], function(err) { + ], function (err) { if (!err) { // Tasks inserted successfully. } @@ -393,7 +391,7 @@ Entity.prototype.testBatchUpsert = function(callback) { ], callback); }; -Entity.prototype.testBatchLookup = function(callback) { +Entity.prototype.testBatchLookup = function (callback) { var taskKey1 = this.datastore.key(['Task', 1]); var taskKey2 = this.datastore.key(['Task', 2]); @@ -402,7 +400,7 @@ Entity.prototype.testBatchLookup = function(callback) { datastore.get([ taskKey1, taskKey2 - ], function(err, tasks) { + ], function (err, tasks) { if (!err) { // Tasks retrieved successfully. } @@ -415,7 +413,7 @@ Entity.prototype.testBatchLookup = function(callback) { ], callback); }; -Entity.prototype.testBatchDelete = function(callback) { +Entity.prototype.testBatchDelete = function (callback) { var taskKey1 = this.datastore.key(['Task', 1]); var taskKey2 = this.datastore.key(['Task', 2]); @@ -423,7 +421,7 @@ Entity.prototype.testBatchDelete = function(callback) { datastore.delete([ taskKey1, taskKey2 - ], function(err) { + ], function (err) { if (!err) { // Tasks deleted successfully. } @@ -436,18 +434,15 @@ Entity.prototype.testBatchDelete = function(callback) { ], callback); }; -function Index(projectId) { +function Index (projectId) { var options = { projectId: projectId }; - if (keyFile) { - options.keyFilename = keyFile; - } this.datastore = gcloud.datastore(options); } -Index.prototype.testUnindexedPropertyQuery = function(callback) { +Index.prototype.testUnindexedPropertyQuery = function (callback) { var datastore = this.datastore; // [START unindexed_property_query] @@ -458,7 +453,7 @@ Index.prototype.testUnindexedPropertyQuery = function(callback) { this.datastore.runQuery(query, callback); }; -Index.prototype.testExplodingProperties = function(callback) { +Index.prototype.testExplodingProperties = function (callback) { var original = datastore.key; datastore.key = this.datastore.key; @@ -487,18 +482,15 @@ Index.prototype.testExplodingProperties = function(callback) { this.datastore.save(task, callback); }; -function Metadata(projectId) { +function Metadata (projectId) { var options = { projectId: projectId }; - if (keyFile) { - options.keyFilename = keyFile; - } this.datastore = gcloud.datastore(options); } -Metadata.prototype.testNamespaceRunQuery = function(callback) { +Metadata.prototype.testNamespaceRunQuery = function (callback) { var self = this; datastore.createQuery = this.datastore.createQuery; @@ -515,7 +507,7 @@ Metadata.prototype.testNamespaceRunQuery = function(callback) { }), data: {} } - ], function(err) { + ], function (err) { if (err) { callback(err); return; @@ -528,15 +520,16 @@ Metadata.prototype.testNamespaceRunQuery = function(callback) { .filter('__key__', '>=', datastore.key(['__namespace__', startNamespace])) .filter('__key__', '<', datastore.key(['__namespace__', endNamespace])); - datastore.runQuery(query, function(err, entities) { + datastore.runQuery(query, function (err, entities) { if (err) { // An error occurred while running the query. return; } - var namespaces = entities.map(function(entity) { + var namespaces = entities.map(function (entity) { return entity.key.path.pop(); }); + console.log('namespaces', namespaces); }); // [END namespace_run_query] @@ -544,7 +537,7 @@ Metadata.prototype.testNamespaceRunQuery = function(callback) { }); }; -Metadata.prototype.testKindRunQuery = function(callback) { +Metadata.prototype.testKindRunQuery = function (callback) { datastore.createQuery = this.datastore.createQuery; // jshint unused:false @@ -552,29 +545,30 @@ Metadata.prototype.testKindRunQuery = function(callback) { var query = datastore.createQuery('__kind__') .select('__key__'); - datastore.runQuery(query, function(err, entities) { + datastore.runQuery(query, function (err, entities) { if (err) { // An error occurred while running the query. return; } - var kinds = entities.map(function(entity) { + var kinds = entities.map(function (entity) { return entity.key.path.pop(); }); + console.log('kinds', kinds); }); // [END kind_run_query] this.datastore.runQuery(query, callback); }; -Metadata.prototype.testPropertyRunQuery = function(callback) { +Metadata.prototype.testPropertyRunQuery = function (callback) { datastore.createQuery = this.datastore.createQuery; // [START property_run_query] var query = datastore.createQuery('__property__') .select('__key__'); - datastore.runQuery(query, function(err, entities) { + datastore.runQuery(query, function (err, entities) { if (err) { // An error occurred while running the query. return; @@ -582,7 +576,7 @@ Metadata.prototype.testPropertyRunQuery = function(callback) { var propertiesByKind = {}; - entities.forEach(function(entity) { + entities.forEach(function (entity) { var kind = entity.key.path[1]; var propertyName = entity.key.path[3]; @@ -595,7 +589,7 @@ Metadata.prototype.testPropertyRunQuery = function(callback) { this.datastore.runQuery(query, callback); }; -Metadata.prototype.testPropertyByKindRunQuery = function(callback) { +Metadata.prototype.testPropertyByKindRunQuery = function (callback) { var datastore = this.datastore; // jshint camelcase:false @@ -605,7 +599,7 @@ Metadata.prototype.testPropertyByKindRunQuery = function(callback) { var query = datastore.createQuery('__property__') .hasAncestor(ancestorKey); - datastore.runQuery(query, function(err, entities) { + datastore.runQuery(query, function (err, entities) { if (err) { // An error occurred while running the query. return; @@ -613,7 +607,7 @@ Metadata.prototype.testPropertyByKindRunQuery = function(callback) { var representationsByProperty = {}; - entities.forEach(function(entity) { + entities.forEach(function (entity) { var propertyName = entity.key.path.pop(); var propertyType = entity.data.property_representation; @@ -625,14 +619,11 @@ Metadata.prototype.testPropertyByKindRunQuery = function(callback) { this.datastore.runQuery(query, callback); }; -function Query(projectId) { +function Query (projectId) { var options = { projectId: projectId }; - if (keyFile) { - options.keyFilename = keyFile; - } this.datastore = gcloud.datastore(options); this.basicQuery = this.getBasicQuery(); @@ -640,7 +631,7 @@ function Query(projectId) { this.ancestorQuery = this.getAncestorQuery(); } -Query.prototype.getBasicQuery = function() { +Query.prototype.getBasicQuery = function () { var datastore = this.datastore; // [START basic_query] @@ -655,7 +646,7 @@ Query.prototype.getBasicQuery = function() { return query; }; -Query.prototype.getProjectionQuery = function() { +Query.prototype.getProjectionQuery = function () { var datastore = this.datastore; // [START projection_query] @@ -666,7 +657,7 @@ Query.prototype.getProjectionQuery = function() { return query; }; -Query.prototype.getAncestorQuery = function() { +Query.prototype.getAncestorQuery = function () { var datastore = this.datastore; // [START ancestor_query] @@ -679,12 +670,12 @@ Query.prototype.getAncestorQuery = function() { return query; }; -Query.prototype.testRunQuery = function(callback) { +Query.prototype.testRunQuery = function (callback) { var query = this.basicQuery; // jshint unused:false // [START run_query] - datastore.runQuery(query, function(err, tasks) { + datastore.runQuery(query, function (err, tasks) { if (!err) { // Task entities found. } @@ -694,7 +685,7 @@ Query.prototype.testRunQuery = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testPropertyFilter = function(callback) { +Query.prototype.testPropertyFilter = function (callback) { var datastore = this.datastore; // [START property_filter] @@ -705,7 +696,7 @@ Query.prototype.testPropertyFilter = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testCompositeFilter = function(callback) { +Query.prototype.testCompositeFilter = function (callback) { var datastore = this.datastore; // [START composite_filter] @@ -717,7 +708,7 @@ Query.prototype.testCompositeFilter = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testKeyFilter = function(callback) { +Query.prototype.testKeyFilter = function (callback) { var datastore = this.datastore; // [START key_filter] @@ -728,7 +719,7 @@ Query.prototype.testKeyFilter = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testAscendingSort = function(callback) { +Query.prototype.testAscendingSort = function (callback) { var datastore = this.datastore; // [START ascending_sort] @@ -739,7 +730,7 @@ Query.prototype.testAscendingSort = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testDescendingSort = function(callback) { +Query.prototype.testDescendingSort = function (callback) { var datastore = this.datastore; // [START descending_sort] @@ -752,7 +743,7 @@ Query.prototype.testDescendingSort = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testMultiSort = function(callback) { +Query.prototype.testMultiSort = function (callback) { var datastore = this.datastore; // [START multi_sort] @@ -766,7 +757,7 @@ Query.prototype.testMultiSort = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testKindlessQuery = function(callback) { +Query.prototype.testKindlessQuery = function (callback) { var datastore = this.datastore; var lastSeenKey = this.datastore.key(['Task', Date.now()]); @@ -779,16 +770,16 @@ Query.prototype.testKindlessQuery = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testRunQueryProjection = function(callback) { +Query.prototype.testRunQueryProjection = function (callback) { var self = this; var query = this.projectionQuery; // Overwrite the mock to actually run the query. - datastore.runQuery = function(query, queryCallback) { + datastore.runQuery = function (query, queryCallback) { // Restore the mock. - datastore.runQuery = function() {}; + datastore.runQuery = function () {}; - self.datastore.runQuery(query, function(err) { + self.datastore.runQuery(query, function (err) { if (err) { return callback(err); } @@ -808,13 +799,13 @@ Query.prototype.testRunQueryProjection = function(callback) { var priorities = []; var percentCompletes = []; - datastore.runQuery(query, function(err, tasks) { + datastore.runQuery(query, function (err, tasks) { if (err) { // An error occurred while running the query. return; } - tasks.forEach(function(task) { + tasks.forEach(function (task) { priorities.push(task.data.priority); percentCompletes.push(task.data.percent_complete); }); @@ -822,7 +813,7 @@ Query.prototype.testRunQueryProjection = function(callback) { // [END run_query_projection] }; -Query.prototype.testKeysOnlyQuery = function(callback) { +Query.prototype.testKeysOnlyQuery = function (callback) { var datastore = this.datastore; // [START keys_only_query] @@ -834,7 +825,7 @@ Query.prototype.testKeysOnlyQuery = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testDistinctQuery = function(callback) { +Query.prototype.testDistinctQuery = function (callback) { var datastore = this.datastore; // [START distinct_query] @@ -847,7 +838,7 @@ Query.prototype.testDistinctQuery = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testDistinctOnQuery = function(callback) { +Query.prototype.testDistinctOnQuery = function (callback) { var datastore = this.datastore; // [START distinct_on_query] @@ -860,7 +851,7 @@ Query.prototype.testDistinctOnQuery = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testArrayValueInequalityRange = function(callback) { +Query.prototype.testArrayValueInequalityRange = function (callback) { var datastore = this.datastore; // [START array_value_inequality_range] @@ -872,7 +863,7 @@ Query.prototype.testArrayValueInequalityRange = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testArrayValueEquality = function(callback) { +Query.prototype.testArrayValueEquality = function (callback) { var datastore = this.datastore; // [START array_value_equality] @@ -884,7 +875,7 @@ Query.prototype.testArrayValueEquality = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testInequalityRange = function(callback) { +Query.prototype.testInequalityRange = function (callback) { var datastore = this.datastore; // [START inequality_range] @@ -896,7 +887,7 @@ Query.prototype.testInequalityRange = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testInequalityInvalid = function(callback) { +Query.prototype.testInequalityInvalid = function (callback) { var datastore = this.datastore; // [START inequality_invalid] @@ -908,7 +899,7 @@ Query.prototype.testInequalityInvalid = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testEqualAndInequalityRange = function(callback) { +Query.prototype.testEqualAndInequalityRange = function (callback) { var datastore = this.datastore; // [START equal_and_inequality_range] @@ -922,7 +913,7 @@ Query.prototype.testEqualAndInequalityRange = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testInequalitySort = function(callback) { +Query.prototype.testInequalitySort = function (callback) { var datastore = this.datastore; // [START inequality_sort] @@ -935,7 +926,7 @@ Query.prototype.testInequalitySort = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testInequalitySortInvalidNotSame = function(callback) { +Query.prototype.testInequalitySortInvalidNotSame = function (callback) { var datastore = this.datastore; // [START inequality_sort_invalid_not_same] @@ -947,7 +938,7 @@ Query.prototype.testInequalitySortInvalidNotSame = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testInequalitySortInvalidNotFirst = function(callback) { +Query.prototype.testInequalitySortInvalidNotFirst = function (callback) { var datastore = this.datastore; // [START inequality_sort_invalid_not_first] @@ -960,7 +951,7 @@ Query.prototype.testInequalitySortInvalidNotFirst = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testLimit = function(callback) { +Query.prototype.testLimit = function (callback) { var datastore = this.datastore; // [START limit] @@ -971,7 +962,7 @@ Query.prototype.testLimit = function(callback) { this.datastore.runQuery(query, callback); }; -Query.prototype.testCursorPaging = function(callback) { +Query.prototype.testCursorPaging = function (callback) { var pageSize = 1; var pageCursor = ''; @@ -987,7 +978,7 @@ Query.prototype.testCursorPaging = function(callback) { .limit(pageSize) .start(pageCursor); - datastore.runQuery(query, function(err, results, nextQuery) { + datastore.runQuery(query, function (err, results, nextQuery) { if (err) { // An error occurred while running the query. return; @@ -1003,11 +994,12 @@ Query.prototype.testCursorPaging = function(callback) { } else { // No more results exist. } + console.log('nextPageCursor', nextPageCursor); }); // [END cursor_paging] delete datastore.createQuery; - this.datastore.runQuery(query, function(err, results, nextQuery) { + this.datastore.runQuery(query, function (err, results, nextQuery) { if (err) { callback(err); return; @@ -1021,21 +1013,21 @@ Query.prototype.testCursorPaging = function(callback) { }); }; -Query.prototype.testEventualConsistentQuery = function() { +Query.prototype.testEventualConsistentQuery = function () { // [START eventual_consistent_query] // Read consistency cannot be specified in gcloud-node. // [END eventual_consistent_query] }; // [START transactional_update] -function transferFunds(fromKey, toKey, amount, callback) { +function transferFunds (fromKey, toKey, amount, callback) { var error; - datastore.runInTransaction(function(transaction, done) { + datastore.runInTransaction(function (transaction, done) { transaction.get([ fromKey, toKey - ], function(err, accounts) { + ], function (err, accounts) { if (err) { // An error occurred while getting the values. error = err; @@ -1050,25 +1042,21 @@ function transferFunds(fromKey, toKey, amount, callback) { done(); }); - }, function(transactionError) { + }, function (transactionError) { if (transactionError || error) { - callback(transactionError || error); - } else { - // The transaction completed successfully. - callback(); + return callback(transactionError || error); } + // The transaction completed successfully. + callback(); }); } // [END transactional_update] -function Transaction(projectId) { +function Transaction (projectId) { var options = { projectId: projectId }; - if (keyFile) { - options.keyFilename = keyFile; - } this.datastore = gcloud.datastore(options); this.fromKey = this.datastore.key(['Bank', 1, 'Account', 1]); @@ -1078,8 +1066,8 @@ function Transaction(projectId) { this.amountToTransfer = 10; } -Transaction.prototype.restoreBankAccountBalances = function(config, callback) { - var saveArray = config.keys.map(function(key) { +Transaction.prototype.restoreBankAccountBalances = function (config, callback) { + var saveArray = config.keys.map(function (key) { return { key: key, data: { @@ -1091,7 +1079,7 @@ Transaction.prototype.restoreBankAccountBalances = function(config, callback) { this.datastore.save(saveArray, callback); }; -Transaction.prototype.testTransactionalUpdate = function(callback) { +Transaction.prototype.testTransactionalUpdate = function (callback) { var self = this; var fromKey = this.fromKey; @@ -1102,7 +1090,7 @@ Transaction.prototype.testTransactionalUpdate = function(callback) { this.restoreBankAccountBalances({ keys: [fromKey, toKey], balance: originalBalance - }, function(err) { + }, function (err) { if (err) { callback(err); return; @@ -1112,7 +1100,7 @@ Transaction.prototype.testTransactionalUpdate = function(callback) { var datastoreMock = datastore; datastore = self.datastore; - transferFunds(fromKey, toKey, amountToTransfer, function(err) { + transferFunds(fromKey, toKey, amountToTransfer, function (err) { // Restore `datastore` to the mock API. datastore = datastoreMock; @@ -1124,7 +1112,7 @@ Transaction.prototype.testTransactionalUpdate = function(callback) { self.datastore.get([ fromKey, toKey - ], function(err, accounts) { + ], function (err, accounts) { if (err) { callback(err); return; @@ -1144,13 +1132,13 @@ Transaction.prototype.testTransactionalUpdate = function(callback) { }); }; -Transaction.prototype.testTransactionalRetry = function(callback) { +Transaction.prototype.testTransactionalRetry = function (callback) { // Overwrite so the real Datastore instance is used in `transferFunds`. var datastoreMock = datastore; datastore = this.datastore; var originalCallback = callback; - callback = function() { + callback = function () { // Restore `datastore` to the mock API. datastore = datastoreMock; originalCallback.apply(null, arguments); @@ -1162,7 +1150,7 @@ Transaction.prototype.testTransactionalRetry = function(callback) { this.restoreBankAccountBalances({ keys: [fromKey, toKey], balance: this.originalBalance - }, function(err) { + }, function (err) { if (err) { callback(err); return; @@ -1171,7 +1159,7 @@ Transaction.prototype.testTransactionalRetry = function(callback) { // [START transactional_retry] var async = require('async'); - function attemptTransfer(callback) { + function attemptTransfer (callback) { transferFunds(fromKey, toKey, 10, callback); } @@ -1180,7 +1168,7 @@ Transaction.prototype.testTransactionalRetry = function(callback) { }); }; -Transaction.prototype.testTransactionalGetOrCreate = function(callback) { +Transaction.prototype.testTransactionalGetOrCreate = function (callback) { var taskKey = this.datastore.key(['Task', Date.now()]); // Overwrite so the real Datastore instance is used in `transferFunds`. @@ -1188,14 +1176,14 @@ Transaction.prototype.testTransactionalGetOrCreate = function(callback) { datastore = this.datastore; var originalCallback = callback; - callback = function() { + callback = function () { // Restore `datastore` to the mock API. datastore = datastoreMock; originalCallback.apply(null, arguments); }; // [START transactional_get_or_create] - function getOrCreate(taskKey, taskData, callback) { + function getOrCreate (taskKey, taskData, callback) { var error; var taskEntity = { @@ -1203,8 +1191,8 @@ Transaction.prototype.testTransactionalGetOrCreate = function(callback) { data: taskData }; - datastore.runInTransaction(function(transaction, done) { - transaction.get(taskKey, function(err, task) { + datastore.runInTransaction(function (transaction, done) { + transaction.get(taskKey, function (err, task) { if (err) { // An error occurred while getting the values. error = err; @@ -1221,13 +1209,12 @@ Transaction.prototype.testTransactionalGetOrCreate = function(callback) { done(); } }); - }, function(transactionError) { + }, function (transactionError) { if (transactionError || error) { - callback(transactionError || error); - } else { - // The transaction completed successfully. - callback(null, taskEntity); + return callback(transactionError || error); } + // The transaction completed successfully. + callback(null, taskEntity); }); } // [END transactional_get_or_create] @@ -1239,58 +1226,56 @@ Transaction.prototype.testTransactionalGetOrCreate = function(callback) { testWithGetBehavior ], callback); - function testWithCreateBehavior(callback) { - getOrCreate(taskKey, {}, function(err, task) { + function testWithCreateBehavior (callback) { + getOrCreate(taskKey, {}, function (err, task) { if (err) { callback(err); return; } if (!task) { - callback(new Error('Entity was not created successfully.')); - } else { - callback(); + return callback(new Error('Entity was not created successfully.')); } + callback(); }); } - function testWithGetBehavior(callback) { - getOrCreate(taskKey, {}, function(err, task) { + function testWithGetBehavior (callback) { + getOrCreate(taskKey, {}, function (err, task) { if (err) { callback(err); return; } if (!task) { - callback(new Error('Entity was not retrieved successfully.')); - } else { - callback(); + return callback(new Error('Entity was not retrieved successfully.')); } + callback(); }); } }; -Transaction.prototype.testSingleEntityGroupReadOnly = function(callback) { +Transaction.prototype.testSingleEntityGroupReadOnly = function (callback) { // Overwrite so the real Datastore instance is used in `transferFunds`. var datastoreMock = datastore; datastore = this.datastore; var originalCallback = callback; - callback = function() { + callback = function () { // Restore `datastore` to the mock API. datastore = datastoreMock; originalCallback.apply(null, arguments); }; // [START transactional_single_entity_group_read_only] - function getTaskListEntities(callback) { + function getTaskListEntities (callback) { var error; var taskListEntities; - datastore.runInTransaction(function(transaction, done) { + datastore.runInTransaction(function (transaction, done) { var taskListKey = datastore.key(['TaskList', 'default']); - datastore.get(taskListKey, function(err) { + datastore.get(taskListKey, function (err) { if (err) { error = err; transaction.rollback(done); @@ -1300,7 +1285,7 @@ Transaction.prototype.testSingleEntityGroupReadOnly = function(callback) { var query = datastore.createQuery('Task') .hasAncestor(taskListKey); - datastore.runQuery(query, function(err, entities) { + datastore.runQuery(query, function (err, entities) { if (err) { // An error occurred while running the query. error = err; @@ -1312,28 +1297,25 @@ Transaction.prototype.testSingleEntityGroupReadOnly = function(callback) { done(); }); }); - - }, function(transactionError) { + }, function (transactionError) { if (transactionError || error) { - callback(transactionError || error); - } else { - // The transaction completed successfully. - callback(null, taskListEntities); + return callback(transactionError || error); } + // The transaction completed successfully. + callback(null, taskListEntities); }); } // [END transactional_single_entity_group_read_only] - getTaskListEntities(function(err, entities) { + getTaskListEntities(function (err, entities) { if (err) { callback(err); return; } if (!entities) { - callback(new Error('Entities were not retrieved successfully.')); - } else { - callback(); + return callback(new Error('Entities were not retrieved successfully.')); } + callback(); }); }; diff --git a/datastore/error.js b/datastore/error.js index 844cb24ec1d..94ea22b319c 100644 --- a/datastore/error.js +++ b/datastore/error.js @@ -13,14 +13,15 @@ 'use strict'; +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication var gcloud = require('gcloud'); - -var dataset = gcloud.datastore({ - projectId: process.env.GCLOUD_PROJECT -}); +var dataset = gcloud.datastore(); // [START error] -function runQuery(cb) { +function runQuery (cb) { var query = dataset.createQuery(['Company']).start('badrequest'); dataset.runQuery(query, function (err, entities) { diff --git a/datastore/package.json b/datastore/package.json index 3cd49d3874d..f6285a3520e 100644 --- a/datastore/package.json +++ b/datastore/package.json @@ -8,12 +8,8 @@ "engines": { "node": ">=0.10.x" }, - "scripts": { - "error": "node error.js", - "tasks": "node tasks.js" - }, "dependencies": { "async": "^1.5.2", - "gcloud": "^0.30.3" + "gcloud": "^0.34.0" } } diff --git a/datastore/tasks.js b/datastore/tasks.js index faf3ea9e4d8..0406e48541e 100755 --- a/datastore/tasks.js +++ b/datastore/tasks.js @@ -16,24 +16,17 @@ var input = process.argv.splice(2); var command = input.shift(); -var projectId = process.env.DATASTORE_PROJECT_ID || process.env.GCLOUD_PROJECT; -if (!projectId) { +if (!process.env.GCLOUD_PROJECT) { throw new Error('GCLOUD_PROJECT environment variable required.'); } -var keyFile = process.env.DATASTORE_KEYFILE || - process.env.GOOGLE_APPLICATION_CREDENTIALS; // [START build_service] +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication var gcloud = require('gcloud'); -var options = { - projectId: projectId -}; - -if (keyFile) { - options.keyFilename = keyFile; -} - -var datastore = gcloud.datastore(options); +var datastore = gcloud.datastore(); // [END build_service] /* @@ -64,7 +57,7 @@ gcloud auth login 6. At a command prompt, run the following, where `` is the ID of your Google Cloud Platform project. ```sh -export DATASTORE_PROJECT_ID= +export GCLOUD_PROJECT= ``` 7. Run the application! @@ -74,7 +67,7 @@ npm run tasks */ // [START add_entity] -function addTask(description, callback) { +function addTask (description, callback) { var taskKey = datastore.key('Task'); datastore.save({ @@ -84,7 +77,7 @@ function addTask(description, callback) { description: description, done: false } - }, function(err) { + }, function (err) { if (err) { callback(err); return; @@ -96,16 +89,16 @@ function addTask(description, callback) { // [END add_entity] // [START update_entity] -function markDone(taskId, callback) { +function markDone (taskId, callback) { var error; - datastore.runInTransaction(function(transaction, done) { + datastore.runInTransaction(function (transaction, done) { var taskKey = datastore.key([ 'Task', taskId ]); - transaction.get(taskKey, function(err, task) { + transaction.get(taskKey, function (err, task) { if (err) { // An error occurred while getting the values. error = err; @@ -120,19 +113,18 @@ function markDone(taskId, callback) { // Commit the transaction. done(); }); - }, function(transactionError) { + }, function (transactionError) { if (transactionError || error) { - callback(transactionError || error); - } else { - // The transaction completed successfully. - callback(); + return callback(transactionError || error); } + // The transaction completed successfully. + callback(); }); } // [END update_entity] // [START retrieve_entities] -function listTasks(callback) { +function listTasks (callback) { var query = datastore.createQuery('Task') .order('created'); @@ -141,7 +133,7 @@ function listTasks(callback) { // [END retrieve_entities] // [START delete_entity] -function deleteTask(taskId, callback) { +function deleteTask (taskId, callback) { var taskKey = datastore.key([ 'Task', taskId @@ -152,9 +144,9 @@ function deleteTask(taskId, callback) { // [END delete_entity] // [START format_results] -function formatTasks(tasks) { +function formatTasks (tasks) { return tasks - .map(function(task) { + .map(function (task) { var taskKey = task.key.path.pop(); var status; @@ -171,25 +163,26 @@ function formatTasks(tasks) { // [END format_results] if (module === require.main) { + var taskId; + switch (command) { case 'new': { - addTask(input, function(err, taskKey) { + addTask(input, function (err, taskKey) { if (err) { throw err; } - var taskId = taskKey.path.pop(); + taskId = taskKey.path.pop(); console.log('Task %d created successfully.', taskId); }); break; } - case 'done': { - var taskId = parseInt(input, 10); + taskId = parseInt(input, 10); - markDone(taskId, function(err) { + markDone(taskId, function (err) { if (err) { throw err; } @@ -199,9 +192,8 @@ if (module === require.main) { break; } - case 'list': { - listTasks(function(err, tasks) { + listTasks(function (err, tasks) { if (err) { throw err; } @@ -211,11 +203,10 @@ if (module === require.main) { break; } - case 'delete': { - var taskId = parseInt(input, 10); + taskId = parseInt(input, 10); - deleteTask(taskId, function(err) { + deleteTask(taskId, function (err) { if (err) { throw err; } @@ -225,7 +216,6 @@ if (module === require.main) { break; } - default: { // Only print usage if this file is being executed directly if (module === require.main) { diff --git a/logging/export.js b/logging/export.js index 313f8ea2673..0ef90b35b76 100644 --- a/logging/export.js +++ b/logging/export.js @@ -14,14 +14,11 @@ 'use strict'; // [START setup] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // Get a reference to the logging component var logging = gcloud.logging(); @@ -31,7 +28,7 @@ var logging = gcloud.logging(); /** * @param {Function} callback Callback function. */ -function listSinksExample(callback) { +function listSinksExample (callback) { // list all sinks in the authenticated project logging.getSinks(function (err, sinks) { if (err) { @@ -51,7 +48,7 @@ function listSinksExample(callback) { * @param {Object} config Configuration options for the new sink. * @param {Function} callback Callback function. */ -function createSinkExample(sinkName, config, callback) { +function createSinkExample (sinkName, config, callback) { // create a new sink in the authenticated project // // This method only works if you are authenticated as yourself, e.g. using the @@ -74,7 +71,7 @@ function createSinkExample(sinkName, config, callback) { * @param {Object} config New configuration options for the sink. * @param {Function} callback Callback function. */ -function updateSinkExample(sinkName, config, callback) { +function updateSinkExample (sinkName, config, callback) { // Get a reference to an existing sink var sink = logging.sink(sinkName); @@ -98,7 +95,7 @@ function updateSinkExample(sinkName, config, callback) { * @param {string} sinkName Name of the sink to delete. * @param {Function} callback Callback function. */ -function deleteSinkExample(sinkName, callback) { +function deleteSinkExample (sinkName, callback) { // Get a reference to an existing sink var sink = logging.sink(sinkName); diff --git a/logging/fluent.js b/logging/fluent.js index 2965b0e7d80..675b2a247d6 100644 --- a/logging/fluent.js +++ b/logging/fluent.js @@ -22,15 +22,15 @@ app.get('*', function (req, res, next) { // [START fluent] var structuredLogger = require('fluent-logger').createFluentSender('myapp', { - host: 'localhost', - port: 24224, - timeout: 3.0 + host: 'localhost', + port: 24224, + timeout: 3.0 }); var report = function (err, req) { var payload = { serviceContext: { - service: 'myapp', + service: 'myapp' }, message: err.stack, context: { @@ -40,7 +40,7 @@ var report = function (err, req) { referrer: req.header('Referer'), userAgent: req.header('User-Agent'), remoteIp: req.ip, - responseStatusCode: 500, + responseStatusCode: 500 } } }; diff --git a/logging/list.js b/logging/list.js index aec74207bee..908a98794fe 100644 --- a/logging/list.js +++ b/logging/list.js @@ -15,26 +15,21 @@ // [START list] // [START auth] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample -var projectId = process.env.GCLOUD_PROJECT; - -// [START require] -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); -// [END require] -// [END auth] +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // Get a reference to the logging component var logging = gcloud.logging(); +// [END auth] /** * @param {Object} [options] Configuration options for the request. * @param {Function} callback Callback function. */ -function listExample(options, callback) { +function listExample (options, callback) { if (typeof options === 'function') { callback = options; } diff --git a/logging/package.json b/logging/package.json index 53a125b670b..ffb83d67506 100644 --- a/logging/package.json +++ b/logging/package.json @@ -15,7 +15,7 @@ }, "dependencies": { "express": "^4.13.4", - "fluent-logger": "^1.1.0", - "gcloud": "^0.30.3" + "fluent-logger": "^1.1.1", + "gcloud": "^0.34.0" } } diff --git a/logging/write.js b/logging/write.js index 77f38bce7a0..d457d5dd1bf 100644 --- a/logging/write.js +++ b/logging/write.js @@ -18,14 +18,11 @@ var async = require('async'); // [START write] // [START setup] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // Get a reference to the logging component var logging = gcloud.logging(); @@ -35,7 +32,7 @@ var logging = gcloud.logging(); * @param {string} logName Name of the log to write to. * @param {Function} callback Callback function. */ -function writeExample(logName, callback) { +function writeExample (logName, callback) { // Get a reference to an existing log var log = logging.log(logName); @@ -83,7 +80,7 @@ function writeExample(logName, callback) { * @param {string} logName Name of the log to delete. * @param {Function} callback Callback function. */ -function deleteLogExample(logName, callback) { +function deleteLogExample (logName, callback) { // Get a reference to an existing log var log = logging.log(logName); diff --git a/monitoring/create_custom_metric.js b/monitoring/create_custom_metric.js index cbf62eb9449..c0fb3d36838 100644 --- a/monitoring/create_custom_metric.js +++ b/monitoring/create_custom_metric.js @@ -33,7 +33,7 @@ var monitoringScopes = [ /** * Returns the current timestamp in RFC33339 with milliseconds format. */ -function getNow() { +function getNow () { var d = new Date(); return JSON.parse(JSON.stringify(d).replace('Z', '000Z')); } @@ -42,7 +42,7 @@ function getNow() { * Returns an hour ago in RFC33339 with milliseconds format. This is used * to start the window to view the metric written in. */ -function getStartTime() { +function getStartTime () { var d = new Date(); d.setHours(d.getHours() - 1); return JSON.parse(JSON.stringify(d).replace('Z', '000Z')); @@ -54,7 +54,7 @@ var CUSTOM_METRIC_DOMAIN = 'custom.googleapis.com'; * Constructor function. The CustomMetrics class stores the type of metric * in its instance class allowing unique ones to be used in tests. */ -function CustomMetrics(projectName, metricType) { +function CustomMetrics (projectName, metricType) { this.projectResource = 'projects/' + projectName; this.metricType = CUSTOM_METRIC_DOMAIN + '/' + metricType; this.metricName = this.projectResource + @@ -250,7 +250,7 @@ exports.main = function (projectId, name, cb) { }, 5000); }, function (cb) { - setTimeout(function() { + setTimeout(function () { customMetrics.listTimeSeries(authClient, cb); }, 5000); }, diff --git a/monitoring/list_resources.js b/monitoring/list_resources.js index 14fcb3f1e27..9d022ba3a0f 100644 --- a/monitoring/list_resources.js +++ b/monitoring/list_resources.js @@ -32,7 +32,7 @@ var METRIC = 'compute.googleapis.com/instance/cpu/usage_time'; /** * Returns an hour ago minus 5 minutes in RFC33339 format. */ -function getStartTime() { +function getStartTime () { var d = new Date(); d.setHours(d.getHours() - 1); d.setMinutes(d.getMinutes() - 5); @@ -42,7 +42,7 @@ function getStartTime() { /** * Returns an hour ago in RFC33339 format. */ -function getEndTime() { +function getEndTime () { var d = new Date(); d.setHours(d.getHours() - 1); return JSON.parse(JSON.stringify(d).replace('Z', '000Z')); @@ -162,14 +162,14 @@ exports.main = function (projectId, cb) { cb ); }, - function(cb) { + function (cb) { ListResources.listMetricDescriptors( authClient, projectName, cb ); }, - function(cb) { + function (cb) { ListResources.listTimeseries( authClient, projectName, diff --git a/monitoring/package.json b/monitoring/package.json index 55ac729f179..fee778f6068 100644 --- a/monitoring/package.json +++ b/monitoring/package.json @@ -8,7 +8,7 @@ "node": ">=0.10.x" }, "dependencies": { - "async":"^1.5.0", - "googleapis": "^3.1.0" + "async":"^1.5.2", + "googleapis": "^7.1.0" } } diff --git a/package.json b/package.json index 5281ff185f2..7392ca53c09 100644 --- a/package.json +++ b/package.json @@ -23,28 +23,49 @@ "type": "git", "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git" }, + "semistandard": { + "globals": [ + "after", + "afterEach", + "before", + "beforeEach", + "describe", + "it" + ], + "ignore": [ + "appengine/bower/public/bower_components/**", + "appengine/geddy/**", + "appengine/kraken/**", + "appengine/loopback/**", + "appengine/parse-server/cloud/main.js", + "appengine/sails/**", + "appengine/webpack/dist/**", + "**/node_modules/**", + "coverage/" + ] + }, "scripts": { - "jshint": "jshint --exclude-path=.jshintignore .", - "deps_appengine": "ava --match='*: dependencies should install*'", "ava": "ava --match='!*: dependencies should install*'", "ava:deps": "npm run deps_appengine && npm run ava", "cover": "npm run deps_appengine && nyc ava --match='!*: dependencies should install*'", - "report": "nyc report --reporter=lcov | codecov", - "report-html": "nyc report --reporter=html", - "deps_gce": "cd computeengine; npm i; cd ../", + "deps_appengine": "ava --match='*: dependencies should install*'", "deps_bigquery": "cd bigquery; npm i; cd ../", - "deps_speech": "cd speech; npm i; cd ../", + "deps_computeengine": "cd computeengine; npm i; cd ../", "deps_datastore": "cd datastore; npm i; cd ../", - "deps_pubsub": "cd pubsub; npm i; cd ../", + "deps_functions": "cd functions/uuid; npm i; cd ../..", + "deps_logging": "cd logging; npm i; cd ../", "deps_monitoring": "cd monitoring; npm i; cd ../", - "deps_storage": "cd storage; npm i; cd ../", "deps_prediction": "cd prediction; npm i; cd ../", - "deps_logging": "cd logging; npm i; cd ../", + "deps_pubsub": "cd pubsub; npm i; cd ../", + "deps_speech": "cd speech; npm i; cd ../", + "deps_storage": "cd storage; npm i; cd ../", "deps_vision": "cd vision; npm i; cd ../", - "deps_functions": "cd functions/uuid; npm i; cd ../..", + "lint": "semistandard \"**/*.js\"", "pretest_geddy": "cd appengine/geddy; npm i geddy; GEDDY_SECRET=config/secrets.json; [[ -f $GEDDY_SECRET ]] || echo '{}' > $GEDDY_SECRET && node node_modules/.bin/geddy gen secret; cd ../..;", - "pretest": "npm run deps_vision; npm run deps_gce; npm run deps_bigquery; npm run deps_datastore; npm run deps_monitoring; npm run deps_storage; npm run deps_pubsub; npm run deps_prediction; npm run deps_logging; npm run deps_functions; npm run deps_speech; npm run pretest_geddy;", - "test": "npm run jshint && npm run cover" + "pretest": "npm run deps_vision; npm run deps_computeengine; npm run deps_bigquery; npm run deps_datastore; npm run deps_monitoring; npm run deps_storage; npm run deps_pubsub; npm run deps_prediction; npm run deps_logging; npm run deps_functions; npm run deps_speech; npm run pretest_geddy;", + "report": "nyc report --reporter=lcov | codecov", + "report-html": "nyc report --reporter=html", + "test": "npm run lint && npm run cover" }, "ava": { "files": [ @@ -52,13 +73,10 @@ ] }, "devDependencies": { - "async": "^1.5.2", - "ava": "^0.13.0", + "ava": "^0.14.0", "codecov": "^1.0.1", - "jshint": "~2.9.1", - "nyc": "^6.1.1", - "proxyquire": "^1.7.4", - "request": "^2.70.0", - "supertest": "^1.2.0" + "nodejs-repo-tools": "git+https://github.com/GoogleCloudPlatform/nodejs-repo-tools.git#bbbb6035d77671eb053dbe6b6f0e3ff983f79639", + "nyc": "^6.4.4", + "semistandard": "^8.0.0" } } diff --git a/prediction/hostedmodels.js b/prediction/hostedmodels.js index aa8a806d413..eb7c643fa44 100644 --- a/prediction/hostedmodels.js +++ b/prediction/hostedmodels.js @@ -17,7 +17,7 @@ var google = require('googleapis'); var hostedmodels = google.prediction('v1.6').hostedmodels; -function auth(callback) { +function auth (callback) { google.auth.getApplicationDefault(function (err, authClient) { if (err) { return callback(err); @@ -45,7 +45,7 @@ function auth(callback) { * e.g. "good morning". * @param {Function} callback Callback function. */ -function predict(phrase, callback) { +function predict (phrase, callback) { auth(function (err, authClient) { if (err) { return callback(err); @@ -64,8 +64,8 @@ function predict(phrase, callback) { } }, function (err, prediction) { if (err) { - return callback(err); - } + return callback(err); + } // Received prediction result console.log('Sentiment for "' + phrase + '": ' + prediction.outputLabel); diff --git a/prediction/package.json b/prediction/package.json index e317db3060d..da15aba03d1 100644 --- a/prediction/package.json +++ b/prediction/package.json @@ -12,6 +12,6 @@ "hostedmodels": "node hostedmodels.js" }, "dependencies": { - "googleapis": "^4.0.0" + "googleapis": "^7.1.0" } } diff --git a/pubsub/iam.js b/pubsub/iam.js index acbbf37aa03..d11de7bdbb9 100644 --- a/pubsub/iam.js +++ b/pubsub/iam.js @@ -26,7 +26,7 @@ var pubsub = subscriptionSample.pubsub; * @param {string} topicName Name of the topic whose policy is to be retrieved. * @param {Function} callback Callback function. */ -function getTopicPolicyExample(topicName, callback) { +function getTopicPolicyExample (topicName, callback) { // Grab a reference to an existing topic var topic = pubsub.topic(topicName); @@ -49,7 +49,7 @@ function getTopicPolicyExample(topicName, callback) { * be retrieved. * @param {Function} callback Callback function. */ -function getSubscriptionPolicyExample(subscriptionName, callback) { +function getSubscriptionPolicyExample (subscriptionName, callback) { // Grab a reference to an existing subscription var subscription = pubsub.subscription(subscriptionName); @@ -70,7 +70,7 @@ function getSubscriptionPolicyExample(subscriptionName, callback) { * @param {string} topicName Name of the topic whose policy is to be updated. * @param {Function} callback Callback function. */ -function setTopicPolicyExample(topicName, callback) { +function setTopicPolicyExample (topicName, callback) { // Grab a reference to an existing topic var topic = pubsub.topic(topicName); @@ -102,7 +102,7 @@ function setTopicPolicyExample(topicName, callback) { * be updated. * @param {Function} callback Callback function. */ -function setSubscriptionPolicyExample(subscriptionName, callback) { +function setSubscriptionPolicyExample (subscriptionName, callback) { // Grab a reference to an existing subscription var subscription = pubsub.subscription(subscriptionName); @@ -133,7 +133,7 @@ function setSubscriptionPolicyExample(subscriptionName, callback) { * @param {string} topicName Name of the topic whose policy is to be tested. * @param {Function} callback Callback function. */ -function testTopicPermissionsExample(topicName, callback) { +function testTopicPermissionsExample (topicName, callback) { // Grab a reference to an existing topic var topic = pubsub.topic(topicName); @@ -161,7 +161,7 @@ function testTopicPermissionsExample(topicName, callback) { * be tested. * @param {Function} callback Callback function. */ -function testSubscriptionPermissionsExample(subscriptionName, callback) { +function testSubscriptionPermissionsExample (subscriptionName, callback) { // Grab a reference to an existing subscription var subscription = pubsub.subscription(subscriptionName); diff --git a/pubsub/package.json b/pubsub/package.json index 7417aefb3a4..6092cc8029c 100644 --- a/pubsub/package.json +++ b/pubsub/package.json @@ -12,6 +12,6 @@ "subscription": "node subscription.js" }, "dependencies": { - "gcloud": "^0.30.3" + "gcloud": "^0.34.0" } } diff --git a/pubsub/subscription.js b/pubsub/subscription.js index f0f31e0c322..61d375950e7 100644 --- a/pubsub/subscription.js +++ b/pubsub/subscription.js @@ -16,14 +16,11 @@ var async = require('async'); // [START auth] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // Get a reference to the pubsub component var pubsub = gcloud.pubsub(); @@ -34,7 +31,7 @@ var pubsub = gcloud.pubsub(); * @param {string} topicName Name for the new topic. * @param {Function} callback Callback function. */ -function createTopicExample(topicName, callback) { +function createTopicExample (topicName, callback) { var topic = pubsub.topic(topicName); // Get the topic if it exists. Create it if it does not exist. @@ -57,7 +54,7 @@ function createTopicExample(topicName, callback) { * @param {string} topicName Name of the topic to delete. * @param {Function} callback Callback function. */ -function deleteTopicExample(topicName, callback) { +function deleteTopicExample (topicName, callback) { var topic = pubsub.topic(topicName); // Delete the topic @@ -78,7 +75,7 @@ function deleteTopicExample(topicName, callback) { * @param {string} subscriptionName Name of the subscription to delete. * @param {Function} callback Callback function. */ -function deleteSubscriptionExample(subscriptionName, callback) { +function deleteSubscriptionExample (subscriptionName, callback) { var subscription = pubsub.subscription(subscriptionName); // Delete the subscription @@ -99,7 +96,7 @@ function deleteSubscriptionExample(subscriptionName, callback) { * @param {string} topicName Name of the topic to which to publish. * @param {Function} callback Callback function. */ -function publishExample(topicName, callback) { +function publishExample (topicName, callback) { // Grab a reference to an existing topic var topic = pubsub.topic(topicName); @@ -122,7 +119,7 @@ function publishExample(topicName, callback) { * @param {string} [pageToken] Page to retrieve. * @param {Function} callback Callback function. */ -function getAllTopicsExample(pageToken, callback) { +function getAllTopicsExample (pageToken, callback) { if (typeof pageToken === 'function') { callback = pageToken; pageToken = undefined; @@ -143,6 +140,9 @@ function getAllTopicsExample(pageToken, callback) { if (nextQuery) { // Grab the remaining pages of topics recursively return getAllTopicsExample(nextQuery.token, function (err, _topics) { + if (err) { + return callback(err); + } if (_topics) { topics = topics.concat(_topics); } @@ -160,7 +160,7 @@ function getAllTopicsExample(pageToken, callback) { * @param {string} [pageToken] Page to retrieve. * @param {Function} callback Callback function. */ -function getAllSubscriptionsExample(pageToken, callback) { +function getAllSubscriptionsExample (pageToken, callback) { if (typeof pageToken === 'function') { callback = pageToken; pageToken = undefined; @@ -184,6 +184,9 @@ function getAllSubscriptionsExample(pageToken, callback) { return getAllSubscriptionsExample( nextQuery.token, function (err, _subscriptions) { + if (err) { + return callback(err); + } if (_subscriptions) { subscriptions = subscriptions.concat(_subscriptions); } @@ -204,7 +207,7 @@ function getAllSubscriptionsExample(pageToken, callback) { * @param {string} subscriptionName Name for the new subscription. * @param {Function} callback Callback function. */ -function subscribeExample(topicName, subscriptionName, callback) { +function subscribeExample (topicName, subscriptionName, callback) { var options = { reuseExisting: true }; @@ -214,8 +217,8 @@ function subscribeExample(topicName, subscriptionName, callback) { options, function (err, subscription, apiResponse) { if (err) { - return callback(err); - } + return callback(err); + } // Got the subscription console.log('Subscribed to ' + topicName); @@ -226,7 +229,7 @@ function subscribeExample(topicName, subscriptionName, callback) { // [END create_subscription] // [START handle_message] -function handleMessageExample(message) { +function handleMessageExample (message) { console.log('received message: ' + message.data); } // [END handle_message] @@ -235,7 +238,7 @@ function handleMessageExample(message) { /** * */ -function pullMessagesExample(topicName, subscriptionName, callback) { +function pullMessagesExample (topicName, subscriptionName, callback) { // Use the "async" library to handle a chain of asynchronous functions async.waterfall([ function (cb) { diff --git a/speech/package.json b/speech/package.json index 51a0432f6bc..eb9c603e5a9 100644 --- a/speech/package.json +++ b/speech/package.json @@ -12,9 +12,9 @@ "recognize": "node recognize" }, "dependencies": { - "googleapis": "^6.1.0" + "googleapis": "^7.1.0" }, "devDependencies": { - "async": "^1.5.0" + "async": "^1.5.2" } } diff --git a/speech/recognize.js b/speech/recognize.js index 15c842338db..86d513f4813 100644 --- a/speech/recognize.js +++ b/speech/recognize.js @@ -26,7 +26,7 @@ var url = 'https://speech.googleapis.com/$discovery/rest'; // [END discovery_doc] // [START authenticating] -function getSpeechService(callback) { +function getSpeechService (callback) { // Acquire credentials google.auth.getApplicationDefault(function (err, authClient) { if (err) { @@ -64,7 +64,7 @@ function getSpeechService(callback) { // [END authenticating] // [START construct_request] -function prepareRequest(inputFile, callback) { +function prepareRequest (inputFile, callback) { fs.readFile(inputFile, function (err, audioFile) { if (err) { return callback(err); @@ -85,7 +85,7 @@ function prepareRequest(inputFile, callback) { } // [END construct_request] -function main(inputFile, callback) { +function main (inputFile, callback) { var requestPayload; async.waterfall([ @@ -97,7 +97,7 @@ function main(inputFile, callback) { getSpeechService(cb); }, // [START send_request] - function sendRequest(speechService, authClient, cb) { + function sendRequest (speechService, authClient, cb) { console.log('Analyzing speech...'); speechService.speech.recognize({ auth: authClient, diff --git a/storage/authSample.js b/storage/authSample.js index 253abdc436c..2283b05f040 100644 --- a/storage/authSample.js +++ b/storage/authSample.js @@ -36,8 +36,8 @@ var google = require('googleapis'); * responds with the list of buckets. */ // [START list_buckets] -function listBucketsExample(projectId, callback) { - google.auth.getApplicationDefault(function(err, authClient) { +function listBucketsExample (projectId, callback) { + google.auth.getApplicationDefault(function (err, authClient) { if (err) { return callback(err); } @@ -61,8 +61,8 @@ function listBucketsExample(projectId, callback) { project: projectId }, function (err, response) { if (err) { - return callback(err); - } + return callback(err); + } console.log('Found ' + response.items.length + ' buckets'); callback(null, response); diff --git a/test/appengine/all.test.js b/test/appengine/all.test.js index bc43f5748a2..5437faa0295 100644 --- a/test/appengine/all.test.js +++ b/test/appengine/all.test.js @@ -22,11 +22,11 @@ var async = require('async'); var cwd = process.cwd(); var projectId = process.env.GCLOUD_PROJECT; -function getPath(dir) { +function getPath (dir) { return path.join(cwd, '/../../', dir); } -function changeScaling(dir) { +function changeScaling (dir) { try { var filepath = getPath(dir) + '/app.yaml'; fs.statSync(filepath); @@ -268,7 +268,7 @@ if (process.env.TRAVIS_NODE_VERSION === '5') { } // Retry the request using exponential backoff up to a maximum number of tries. -function makeRequest(url, numTry, maxTries, cb) { +function makeRequest (url, numTry, maxTries, cb) { request(url, function (err, res, body) { if (err) { if (numTry >= maxTries) { @@ -285,7 +285,7 @@ function makeRequest(url, numTry, maxTries, cb) { // Send a request to the given url and test that the response body has the // expected value -function testRequest(url, sample, cb) { +function testRequest (url, sample, cb) { // Try up to 8 times makeRequest(url, 1, 8, function (err, res, body) { if (err) { @@ -344,8 +344,7 @@ if (process.env.TRAVIS && process.env.DEPLOY_TESTS) { }); } -function testInstallation(sample, done) { - +function testInstallation (sample, done) { // Keep track off whether "done" has been called yet var calledDone = false; @@ -370,7 +369,7 @@ function testInstallation(sample, done) { }); // Exit helper so we don't call "cb" more than once - function finish(err) { + function finish (err) { if (!calledDone) { calledDone = true; done(err); @@ -378,7 +377,7 @@ function testInstallation(sample, done) { } } -function testLocalApp(sample, done) { +function testLocalApp (sample, done) { var calledDone = false; var requestError; @@ -397,7 +396,7 @@ function testLocalApp(sample, done) { var proc = spawn(sample.cmd, sample.args, opts); // Exit helper so we don't call "cb" more than once - function finish(err) { + function finish (err) { if (!calledDone) { calledDone = true; done(err || requestError); @@ -446,8 +445,7 @@ function testLocalApp(sample, done) { } } -function testDeployments(done) { - +function testDeployments (done) { // Only deploy samples that have a projectId var samplesToDeploy = sampleTests.filter(function (sample) { return (sample.deploy && @@ -511,7 +509,7 @@ function testDeployments(done) { }); // Exit helper so we don't call "cb" more than once - function finish(err, result) { + function finish (err, result) { if (!calledDone) { calledDone = true; var intervalId = setInterval(function () { @@ -534,7 +532,7 @@ function testDeployments(done) { var numEnded = 0; - function finishLogs() { + function finishLogs () { numEnded++; if (numEnded === 2) { logStream.end(); diff --git a/test/bigquery/dataset_size.test.js b/test/bigquery/dataset_size.test.js index 9e2c3ef5e18..b05271a494f 100644 --- a/test/bigquery/dataset_size.test.js +++ b/test/bigquery/dataset_size.test.js @@ -23,7 +23,7 @@ test.cb('should return the size of a dataset', function (t) { function (err, size) { t.ifError(err); t.is(typeof size, 'string'); - t.ok(size.indexOf(' GB') === size.length - 3); + t.truthy(size.indexOf(' GB') === size.length - 3); t.end(); } ); diff --git a/test/bigquery/getting_started.test.js b/test/bigquery/getting_started.test.js index 48387b2c07a..223b4b47fa2 100644 --- a/test/bigquery/getting_started.test.js +++ b/test/bigquery/getting_started.test.js @@ -20,7 +20,7 @@ test.cb('should run a query', function (t) { gettingStartedExample.main( function (err, rows) { t.ifError(err); - t.ok(Array.isArray(rows)); + t.truthy(Array.isArray(rows)); t.is(rows.length, 10); t.end(); } diff --git a/test/bigquery/load_data_from_csv.test.js b/test/bigquery/load_data_from_csv.test.js index a388028a539..7f3f6b15bf5 100644 --- a/test/bigquery/load_data_from_csv.test.js +++ b/test/bigquery/load_data_from_csv.test.js @@ -14,9 +14,10 @@ 'use strict'; var async = require('async'); +var path = require('path'); var test = require('ava'); var loadDataFromCsvExample = require('../../bigquery/load_data_from_csv'); -var pathToCsvFile = __dirname + '/../../bigquery/resources/data.csv'; +var pathToCsvFile = path.join(__dirname, '/../../bigquery/resources/data.csv'); var datasetId = 'nodejs_docs_samples'; var tableName = 'test_' + new Date().getTime() + '_' + Math.floor(Math.random() * 10000); diff --git a/test/bigquery/load_data_from_gcs.test.js b/test/bigquery/load_data_from_gcs.test.js index aa3478e4fca..591674fe194 100644 --- a/test/bigquery/load_data_from_gcs.test.js +++ b/test/bigquery/load_data_from_gcs.test.js @@ -1,5 +1,3 @@ - - // Copyright 2016, Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/test/computeengine/mailjet.test.js b/test/computeengine/mailjet.test.js index bb5eb069f0b..048940da1b9 100644 --- a/test/computeengine/mailjet.test.js +++ b/test/computeengine/mailjet.test.js @@ -25,7 +25,7 @@ test.cb('should send an email', function (t) { t.is(arg, 'test'); return { sendMail: function (payload, cb) { - t.same(payload, { + t.deepEqual(payload, { from: 'ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM', to: 'EMAIL@EXAMPLE.COM', subject: 'test email from Node.js on Google Cloud Platform', @@ -38,7 +38,7 @@ test.cb('should send an email', function (t) { } }, 'nodemailer-smtp-transport': function (options) { - t.same(options, { + t.deepEqual(options, { service: 'Mailjet', auth: { user: 'foo', diff --git a/test/computeengine/sendgrid.test.js b/test/computeengine/sendgrid.test.js index a5b065587f2..c2da1f4994e 100644 --- a/test/computeengine/sendgrid.test.js +++ b/test/computeengine/sendgrid.test.js @@ -23,7 +23,7 @@ test.cb('should send an email', function (t) { t.is(key, 'foo'); return { send: function (payload, cb) { - t.same(payload, { + t.deepEqual(payload, { from: 'ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM', to: 'EMAIL@EXAMPLE.COM', subject: 'test email from Node.js on Google Cloud Platform', diff --git a/test/computeengine/vms.test.js b/test/computeengine/vms.test.js index bbb129d5365..38736833abd 100644 --- a/test/computeengine/vms.test.js +++ b/test/computeengine/vms.test.js @@ -19,7 +19,7 @@ var vmsExample = require('../../computeengine/vms'); test.cb('should retrieve vms', function (t) { vmsExample.main(function (err, result) { t.ifError(err); - t.ok(result); + t.truthy(result); t.is(Array.isArray(result), true); t.end(); }); diff --git a/test/computeengine/vms_api.test.js b/test/computeengine/vms_api.test.js index d058e5114a3..5920cf1e1f2 100644 --- a/test/computeengine/vms_api.test.js +++ b/test/computeengine/vms_api.test.js @@ -19,7 +19,7 @@ var vmsExample = require('../../computeengine/vms_api'); test.cb('should retrieve vms', function (t) { vmsExample.main(function (err, result) { t.ifError(err); - t.ok(result); + t.truthy(result); t.end(); }); }); diff --git a/test/datastore/concepts.test.js b/test/datastore/concepts.test.js index 93326fee79f..965225edafe 100644 --- a/test/datastore/concepts.test.js +++ b/test/datastore/concepts.test.js @@ -164,7 +164,7 @@ test.cb.serial('performs an inequality range query', function (t) { test.cb.serial('returns an error from an invalid query', function (t) { query.testInequalityInvalid(function (err) { - t.ok(err); + t.truthy(err); t.end(); }); }); @@ -181,7 +181,7 @@ test.cb.serial( 'returns an error when not sorted on filtered property', function (t) { query.testInequalitySortInvalidNotSame(function (err) { - t.ok(err); + t.truthy(err); t.end(); }); } @@ -191,7 +191,7 @@ test.cb.serial( 'returns an error when not sorted on first filter prop', function (t) { query.testInequalitySortInvalidNotFirst(function (err) { - t.ok(err); + t.truthy(err); t.end(); }); } @@ -201,7 +201,7 @@ test.cb.serial('performs a query with a limit', function (t) { query.testLimit(t.end); }); -test.cb.serial('allows manual pagination through results', function (t) { +test.cb.serial.skip('allows manual pagination through results', function (t) { entity.testBatchUpsert(function (err) { t.ifError(err); setTimeout(function () { diff --git a/test/datastore/error.test.js b/test/datastore/error.test.js index 69f29584d42..b35cb7b37f9 100644 --- a/test/datastore/error.test.js +++ b/test/datastore/error.test.js @@ -18,7 +18,7 @@ var error = require('../../datastore/error.js'); test.cb.serial('should have an error', function (t) { error.runQuery(function (err) { - t.ok(err); + t.truthy(err); t.is(err.code, 400); t.end(); }); diff --git a/test/datastore/tasks.test.js b/test/datastore/tasks.test.js index be8eadd9db5..2a616b3256d 100644 --- a/test/datastore/tasks.test.js +++ b/test/datastore/tasks.test.js @@ -59,7 +59,7 @@ test.cb.serial('should format tasks', function (t) { }); }); -function getTaskId(callback) { +function getTaskId (callback) { tasks.addEntity('description', function (err, taskKey) { if (err) { return callback(err); diff --git a/test/datastore/util.js b/test/datastore/util.js index ffe512f5440..1c47393b60a 100644 --- a/test/datastore/util.js +++ b/test/datastore/util.js @@ -14,17 +14,17 @@ 'use strict'; module.exports = { - deleteEntities: function(datastore, query, callback) { - datastore.runQuery(query, function(err, entities) { + deleteEntities: function (datastore, query, callback) { + datastore.runQuery(query, function (err, entities) { if (err) { return callback(err); } - var keys = entities.map(function(entity) { + var keys = entities.map(function (entity) { return entity.key; }); datastore.delete(keys, callback); }); } -}; \ No newline at end of file +}; diff --git a/test/functions/log.test.js b/test/functions/log.test.js index 14e6ee53fa8..a72a0be5324 100644 --- a/test/functions/log.test.js +++ b/test/functions/log.test.js @@ -56,8 +56,7 @@ test.cb('should write to log 2', function (t) { t.end('message was not printed!'); } } - }, - { + }, { message: 'foo' }); }); @@ -68,8 +67,7 @@ test.cb('should write to log 3', function (t) { t.is(result, logMessage); t.end(); } - }, - { + }, { message: 'foo' }); }); diff --git a/test/logging/export.test.js b/test/logging/export.test.js index f15d50c6b89..b222cc40c66 100644 --- a/test/logging/export.test.js +++ b/test/logging/export.test.js @@ -19,8 +19,8 @@ var exportExample = require('../../logging/export'); test.cb('should list sinks', function (t) { exportExample.main(function (err, sinks) { t.ifError(err); - t.ok(sinks, 'should have received sinks'); - t.ok(Array.isArray(sinks), 'sinks should be an array'); + t.truthy(sinks, 'should have received sinks'); + t.truthy(Array.isArray(sinks), 'sinks should be an array'); t.end(); }); }); diff --git a/test/logging/fluent.test.js b/test/logging/fluent.test.js index 275db0f3e09..d4ba55156a5 100644 --- a/test/logging/fluent.test.js +++ b/test/logging/fluent.test.js @@ -31,7 +31,7 @@ test.cb('should log error', function (t) { 'fluent-logger': { createFluentSender: function (name, options) { t.is(name, 'myapp'); - t.same(options, { + t.deepEqual(options, { host: 'localhost', port: 24224, timeout: 3.0 diff --git a/test/logging/list.test.js b/test/logging/list.test.js index 5a89ec8a703..635c2cd5174 100644 --- a/test/logging/list.test.js +++ b/test/logging/list.test.js @@ -19,10 +19,10 @@ var listExample = require('../../logging/list'); test.cb('should list entries', function (t) { listExample.main(undefined, function (err, entries, nextQuery, apiResponse) { t.ifError(err); - t.ok(entries, 'should have received entries'); - t.ok(Array.isArray(entries), 'entries should be an array'); - t.ok(nextQuery, 'should have received nextQuery'); - t.ok(apiResponse, 'should have received apiResponse'); + t.truthy(entries, 'should have received entries'); + t.truthy(Array.isArray(entries), 'entries should be an array'); + t.truthy(nextQuery, 'should have received nextQuery'); + t.truthy(apiResponse, 'should have received apiResponse'); t.end(); }); }); diff --git a/test/monitoring/create_custom_metric.test.js b/test/monitoring/create_custom_metric.test.js index ebb3dca88d1..94a9850b914 100644 --- a/test/monitoring/create_custom_metric.test.js +++ b/test/monitoring/create_custom_metric.test.js @@ -17,7 +17,7 @@ var test = require('ava'); var customMetricsExample = require('../../monitoring/create_custom_metric'); /** Refactored out to keep lines shorter */ -function getPointValue(timeSeries) { +function getPointValue (timeSeries) { return timeSeries.timeSeries[0].points[0].value.int64Value; } @@ -29,14 +29,14 @@ test.cb('should create and read back a custom metric', function (t) { t.ifError(err); t.is(results.length, 4); // Result of creating metric - t.ok(typeof results[0].name === 'string'); + t.truthy(typeof results[0].name === 'string'); // Result of writing time series - t.same(results[1], {}); + t.deepEqual(results[1], {}); // Result of reading time series - t.ok(typeof getPointValue(results[2]) === 'string'); - t.ok(!isNaN(parseInt(getPointValue(results[2]), 10))); + t.truthy(typeof getPointValue(results[2]) === 'string'); + t.truthy(!isNaN(parseInt(getPointValue(results[2]), 10))); // Result of deleting metric - t.same(results[3], {}); + t.deepEqual(results[3], {}); t.end(); } ); diff --git a/test/monitoring/list_resources.test.js b/test/monitoring/list_resources.test.js index b57e38b02be..aab198f4287 100644 --- a/test/monitoring/list_resources.test.js +++ b/test/monitoring/list_resources.test.js @@ -23,11 +23,11 @@ test.cb('should list a bunch of stuff', function (t) { t.ifError(err); t.is(results.length, 3); // Monitored resources - t.ok(Array.isArray(results[0].resourceDescriptors)); + t.truthy(Array.isArray(results[0].resourceDescriptors)); // Metric descriptors - t.ok(Array.isArray(results[1].metricDescriptors)); + t.truthy(Array.isArray(results[1].metricDescriptors)); // Time series - t.ok(Array.isArray(results[2].timeSeries)); + t.truthy(Array.isArray(results[2].timeSeries)); t.end(); } ); diff --git a/test/prediction/hostedmodels.test.js b/test/prediction/hostedmodels.test.js index a874393491c..0fd5a7766b1 100644 --- a/test/prediction/hostedmodels.test.js +++ b/test/prediction/hostedmodels.test.js @@ -19,7 +19,7 @@ var hostedmodels = require('../../prediction/hostedmodels'); test.cb('should predict', function (t) { hostedmodels.main('good night', function (err, result) { t.ifError(err); - t.ok(result); + t.truthy(result); t.end(); }); }); diff --git a/test/pubsub/iam.test.js b/test/pubsub/iam.test.js index bc58d74886e..c31d74bea2a 100644 --- a/test/pubsub/iam.test.js +++ b/test/pubsub/iam.test.js @@ -33,9 +33,9 @@ test.cb('should run the sample', function (t) { // Got permissions and apiResponse t.is(results[5].length, 2); // Got empty apiResponse - t.same(results[6], {}); + t.deepEqual(results[6], {}); // Got empty apiResponse - t.same(results[7], {}); + t.deepEqual(results[7], {}); t.end(); }); }); diff --git a/test/pubsub/subscription.test.js b/test/pubsub/subscription.test.js index 6f03cc2727c..16a70d90934 100644 --- a/test/pubsub/subscription.test.js +++ b/test/pubsub/subscription.test.js @@ -25,17 +25,17 @@ test.cb('should run the sample', function (t) { // Got subscription and apiResponse t.is(results[1].length, 2); // Got array of topics - t.ok(Array.isArray(results[2])); + t.truthy(Array.isArray(results[2])); // Got array of subscriptions - t.ok(Array.isArray(results[3])); + t.truthy(Array.isArray(results[3])); // Got messageIds and apiResponse t.is(results[4].length, 2); // Got array of messages - t.ok(Array.isArray(results[5])); + t.truthy(Array.isArray(results[5])); // Got empty apiResponse - t.same(results[6], {}); + t.deepEqual(results[6], {}); // Got empty apiResponse - t.same(results[7], {}); + t.deepEqual(results[7], {}); t.end(); }); }); diff --git a/test/speech/recognize.test.js b/test/speech/recognize.test.js index e23d0e60177..6c7d0af613d 100644 --- a/test/speech/recognize.test.js +++ b/test/speech/recognize.test.js @@ -22,10 +22,10 @@ test.cb('should list entries', function (t) { path.resolve('../../speech/resources/audio.raw'), function (err, result) { t.ifError(err); - t.ok(result); - t.ok(result.responses); + t.truthy(result); + t.truthy(result.responses); t.is(result.responses.length, 1); - t.ok(result.responses[0].results); + t.truthy(result.responses[0].results); t.end(); } ); diff --git a/test/storage/authSample.test.js b/test/storage/authSample.test.js index b64337ea0e6..28a484e60fd 100644 --- a/test/storage/authSample.test.js +++ b/test/storage/authSample.test.js @@ -25,7 +25,7 @@ test.cb('should return a list of buckets', function (t) { authSampleExample.main(projectId, function (err, response) { t.ifError(err); - t.ok(response.items.length > 0, 'There should be some buckets.'); + t.truthy(response.items.length > 0, 'There should be some buckets.'); t.is(response.items.filter(function (item) { return item.name === bucketName; }).length, 1, 'There should be a bucket named ' + bucketName); diff --git a/test/vision/labelDetection.test.js b/test/vision/labelDetection.test.js index 330d775e303..5d65af21e72 100644 --- a/test/vision/labelDetection.test.js +++ b/test/vision/labelDetection.test.js @@ -24,7 +24,7 @@ test.cb('should detect labels', function (t) { inputFile, function (err, labels) { t.ifError(err); - t.ok(labels.length > 0); + t.truthy(labels.length > 0); t.end(); } ); diff --git a/test/vision/landmarkDetection.test.js b/test/vision/landmarkDetection.test.js index e917b4417bc..83074e890f2 100644 --- a/test/vision/landmarkDetection.test.js +++ b/test/vision/landmarkDetection.test.js @@ -22,7 +22,7 @@ test.cb('should detect landmarks', function (t) { 'https://cloud-samples-tests.storage.googleapis.com/vision/water.jpg', function (err, landmarks) { t.ifError(err); - t.ok(landmarks.length > 0); + t.truthy(landmarks.length > 0); t.end(); } ); diff --git a/test/vision/textDetection.test.js b/test/vision/textDetection.test.js index 132bf7ae520..69d2e1c3058 100644 --- a/test/vision/textDetection.test.js +++ b/test/vision/textDetection.test.js @@ -23,13 +23,13 @@ test.cb('should detect texts', function (t) { inputDir, function (err, textResponse) { t.ifError(err); - t.ok(Object.keys(textResponse).length > 0); + t.truthy(Object.keys(textResponse).length > 0); textDetectionSample.lookup( ['the', 'sunbeams', 'in'], function (err, hits) { t.ifError(err); - t.ok(hits.length > 0); - t.ok(hits[0].length > 0); + t.truthy(hits.length > 0); + t.truthy(hits[0].length > 0); t.end(); } ); diff --git a/vision/faceDetection.js b/vision/faceDetection.js index 66b2c0a4651..40b9b0a9deb 100644 --- a/vision/faceDetection.js +++ b/vision/faceDetection.js @@ -14,15 +14,11 @@ 'use strict'; // [START auth] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample. See: -// https://github.com/GoogleCloudPlatform/gcloud-node/blob/master/docs/authentication.md -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -var gcloud = require('gcloud')({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); // Get a reference to the vision component var vision = gcloud.vision(); @@ -33,7 +29,7 @@ var fs = require('fs'); /** * Uses the Vision API to detect faces in the given file. */ -function detectFaces(inputFile, callback) { +function detectFaces (inputFile, callback) { // Make a call to the Vision API to detect the faces vision.detectFaces(inputFile, function (err, faces) { if (err) { @@ -48,7 +44,7 @@ function detectFaces(inputFile, callback) { /** * Draws a polygon around the faces, then saves to outputFile. */ -function highlightFaces(inputFile, faces, outputFile, Canvas, callback) { +function highlightFaces (inputFile, faces, outputFile, Canvas, callback) { fs.readFile(inputFile, function (err, image) { if (err) { return callback(err); @@ -89,7 +85,7 @@ function highlightFaces(inputFile, faces, outputFile, Canvas, callback) { } // Run the example -function main(inputFile, outputFile, Canvas, callback) { +function main (inputFile, outputFile, Canvas, callback) { outputFile = outputFile || 'out.png'; detectFaces(inputFile, function (err, faces) { if (err) { diff --git a/vision/labelDetection.js b/vision/labelDetection.js index 79eb13e422b..b8ccc69ea51 100644 --- a/vision/labelDetection.js +++ b/vision/labelDetection.js @@ -19,15 +19,10 @@ var gcloud = require('gcloud'); // [END import_libraries] // [START authenticate] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample. See: -// https://github.com/GoogleCloudPlatform/gcloud-node/blob/master/docs/authentication.md -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -gcloud = gcloud({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication // Get a reference to the vision component var vision = gcloud.vision(); @@ -37,7 +32,7 @@ var vision = gcloud.vision(); * Uses the Vision API to detect labels in the given file. */ // [START construct_request] -function detectLabels(inputFile, callback) { +function detectLabels (inputFile, callback) { // Make a call to the Vision API to detect the labels vision.detectLabels(inputFile, { verbose: true }, function (err, labels) { if (err) { @@ -50,7 +45,7 @@ function detectLabels(inputFile, callback) { // [END construct_request] // Run the example -function main(inputFile, callback) { +function main (inputFile, callback) { detectLabels(inputFile, function (err, labels) { if (err) { return callback(err); diff --git a/vision/landmarkDetection.js b/vision/landmarkDetection.js index 3f6a4a378a7..9b7e2f8c237 100644 --- a/vision/landmarkDetection.js +++ b/vision/landmarkDetection.js @@ -19,15 +19,10 @@ var gcloud = require('gcloud'); // [END import_libraries] // [START authenticate] -// You must set the GOOGLE_APPLICATION_CREDENTIALS and GCLOUD_PROJECT -// environment variables to run this sample. See: -// https://github.com/GoogleCloudPlatform/gcloud-node/blob/master/docs/authentication.md -var projectId = process.env.GCLOUD_PROJECT; - -// Initialize gcloud -gcloud = gcloud({ - projectId: projectId -}); +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication // Get a reference to the vision component var vision = gcloud.vision(); @@ -37,7 +32,7 @@ var vision = gcloud.vision(); * Uses the Vision API to detect landmarks in the given file. */ // [START construct_request] -function detectLandmarks(inputFile, callback) { +function detectLandmarks (inputFile, callback) { var options = { verbose: true }; // Make a call to the Vision API to detect the landmarks @@ -52,7 +47,7 @@ function detectLandmarks(inputFile, callback) { // [END construct_request] // Run the example -function main(inputFile, callback) { +function main (inputFile, callback) { detectLandmarks(inputFile, function (err, landmarks) { if (err) { return callback(err); diff --git a/vision/textDetection.js b/vision/textDetection.js index 2a37e6ce76a..140351ff498 100644 --- a/vision/textDetection.js +++ b/vision/textDetection.js @@ -18,14 +18,19 @@ var async = require('async'); var fs = require('fs'); var path = require('path'); -var gcloud = require('gcloud')(); + +// By default, gcloud will authenticate using the service account file specified +// by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use the +// project specified by the GCLOUD_PROJECT environment variable. See +// https://googlecloudplatform.github.io/gcloud-node/#/docs/guides/authentication +var gcloud = require('gcloud'); var natural = require('natural'); var redis = require('redis'); // Get a reference to the vision component var vision = gcloud.vision(); // [END import_libraries] -function Index() { +function Index () { // Connect to a redis server. var TOKEN_DB = 0; var DOCS_DB = 1; @@ -104,7 +109,7 @@ Index.prototype.setContainsNoText = function (filename, callback) { this.docsClient.set(filename, '', callback); }; -function lookup(words, callback) { +function lookup (words, callback) { var index = new Index(); index.lookup(words, function (err, hits) { index.quit(); @@ -112,14 +117,14 @@ function lookup(words, callback) { return callback(err); } words.forEach(function (word, i) { - console.log('hits for \"' + word + '\":', hits[i].join(', ')); + console.log('hits for "' + word + '":', hits[i].join(', ')); }); callback(null, hits); }); } // [START extract_descrs] -function extractDescription(texts) { +function extractDescription (texts) { var document = ''; texts.forEach(function (text) { document += (text.desc || ''); @@ -127,7 +132,7 @@ function extractDescription(texts) { return document; } -function extractDescriptions(filename, index, texts, callback) { +function extractDescriptions (filename, index, texts, callback) { if (texts.length) { index.add(filename, extractDescription(texts), callback); } else { @@ -138,7 +143,7 @@ function extractDescriptions(filename, index, texts, callback) { // [END extract_descrs] // [START get_text] -function getTextFromFiles(index, inputFiles, callback) { +function getTextFromFiles (index, inputFiles, callback) { var options = { verbose: true }; // Make a call to the Vision API to detect text @@ -172,7 +177,7 @@ function getTextFromFiles(index, inputFiles, callback) { } // Run the example -function main(inputDir, callback) { +function main (inputDir, callback) { var index = new Index(); async.waterfall([