From 9dbe7fbae01f104eaa45d9c0b8356e7de1568237 Mon Sep 17 00:00:00 2001 From: muraliQlogic Date: Tue, 23 Oct 2018 02:00:30 +0530 Subject: [PATCH 1/9] Samples to use async/await and mocha --- samples/package.json | 5 +- samples/startup-script/index.js | 162 +++++++++--------- samples/startup-script/package.json | 4 +- .../startup-script/system-test/index.test.js | 64 +++---- samples/system-test/vms.test.js | 26 +-- samples/system-test/vms_api.test.js | 25 +-- samples/test/mailjet.test.js | 69 ++++---- samples/test/sendgrid.test.js | 74 ++++---- 8 files changed, 224 insertions(+), 205 deletions(-) diff --git a/samples/package.json b/samples/package.json index 3f2cc398..c0cae987 100644 --- a/samples/package.json +++ b/samples/package.json @@ -9,7 +9,7 @@ "node": ">=8" }, "scripts": { - "system-test": "ava -T 20s --verbose system-test/*.test.js", + "system-test": "mocha system-test/*.js --timeout 600000", "startup-test": "ava -T 200s --verbose startup-script/system-test/*.test.js", "test": "npm run system-test && npm run startup-test" }, @@ -22,7 +22,6 @@ }, "devDependencies": { "@google-cloud/nodejs-repo-tools": "^2.3.1", - "ava": "^0.25.0", - "proxyquire": "^2.0.1" + "mocha": "^5.0.0" } } diff --git a/samples/startup-script/index.js b/samples/startup-script/index.js index b9e9849c..ad7bf9d2 100644 --- a/samples/startup-script/index.js +++ b/samples/startup-script/index.js @@ -26,85 +26,85 @@ const zone = compute.zone('us-central1-a'); function createVm(name, callback) { // Create a new VM, using default ubuntu image. The startup script // installs apache and a custom homepage. - const config = { - os: 'ubuntu', - http: true, - metadata: { - items: [ - { - key: 'startup-script', - value: `#! /bin/bash - - # Installs apache and a custom homepage - apt-get update - apt-get install -y apache2 - cat < /var/www/html/index.html - -

Hello World

-

This page was created from a simple start-up script!

`, + (async() =>{ + try{ + const config = { + os: 'ubuntu', + http: true, + metadata: { + items: [ + { + key: 'startup-script', + value: `#! /bin/bash + + # Installs apache and a custom homepage + apt-get update + apt-get install -y apache2 + cat < /var/www/html/index.html + +

Hello World

+

This page was created from a simple start-up script!

`, + }, + ], }, - ], - }, - }; - - const vm = zone.vm(name); - - vm.create(config) - .then(data => { - const operation = data[1]; - return operation.promise(); - }) - .then(() => { - return vm.getMetadata(); - }) - .then(data => { - const metadata = data[0]; - + }; + const vm = zone.vm(name); + + const data = await vm.create(config); + console.log('Creating VM ...'); + await data[1].promise(); + const metadata = await vm.getMetadata(); + // External IP of the VM. - const ip = metadata.networkInterfaces[0].accessConfigs[0].natIP; + const ip = metadata[0].networkInterfaces[0].accessConfigs[0].natIP; console.log(`Booting new VM with IP http://${ip}...`); // Ping the VM to determine when the HTTP server is ready. let waiting = true; - const timer = setInterval( - ip => { - http - .get('http://' + ip, res => { - const statusCode = res.statusCode; - if (statusCode === 200 && waiting) { - waiting = false; - clearTimeout(timer); - // HTTP server is ready. - console.log('Ready!'); - callback(null, ip); - } - }) - .on('error', () => { - // HTTP server is not ready yet. - process.stdout.write('.'); - }); - }, - 2000, - ip - ); - }) - .catch(err => callback(err)); + const timer = setInterval( + ip => { + http + .get('http://' + ip, res => { + const statusCode = res.statusCode; + if (statusCode === 200 && waiting) { + waiting = false; + clearTimeout(timer); + // HTTP server is ready. + console.log('Ready!'); + callback(null, ip); + } + }) + .on('error', () => { + // HTTP server is not ready yet. + process.stdout.write('.'); + }); + }, + 2000, + ip + ); + + }catch(err){ + callback(err); + } + })(); + } // List all VMs and their external IPs in a given zone. // callback(error, [[name, ip], [name, ip], ...]) function listVms(callback) { - zone - .getVMs() - .then(data => { + (async () => { + try{ + const data = await zone.getVMs(); const vms = data[0]; - const results = vms.map(vm => vm.getMetadata()); - return Promise.all(results); - }) - .then(res => + const results=[]; + for(var i in vms){ + var metadata = await vms[i].getMetadata(); + results.push(metadata); + } callback( null, - res.map(data => { + results.map(data => { return { ip: data[0]['networkInterfaces'][0]['accessConfigs'] ? data[0]['networkInterfaces'][0]['accessConfigs'][0]['natIP'] @@ -112,24 +112,28 @@ function listVms(callback) { name: data[0].name, }; }) - ) ) - .catch(err => callback(err)); + } + catch(err){ + callback(err); + } + })(); } function deleteVm(name, callback) { - const vm = zone.vm(name); - vm.delete() - .then(data => { - console.log('Deleting ...'); - const operation = data[0]; - return operation.promise(); - }) - .then(() => { - // VM deleted - callback(null, name); - }) - .catch(err => callback(err)); + (async () => { + try{ + const vm = zone.vm(name); + const data = await vm.delete() + console.log('Deleting ...'); + await data[0].promise(); + // VM deleted + callback(null, name); + }catch(err){ + callback(err); + } + })(); + } exports.create = (name, cb) => { diff --git a/samples/startup-script/package.json b/samples/startup-script/package.json index c8e13f7c..888a1d31 100644 --- a/samples/startup-script/package.json +++ b/samples/startup-script/package.json @@ -8,11 +8,11 @@ }, "devDependencies": { "@google-cloud/nodejs-repo-tools": "^2.3.0", - "ava": "^0.25.0", + "mocha": "^5.0.0", "uuid": "^3.2.1" }, "scripts": { - "test": "ava -T 600s --verbose system-test/*.test.js", + "test": "mocha system-test/*.js --timeout 600000", "start": "node -e 'require(\"./index.js\").create(\"vm-with-apache\", console.log)'", "delete": "node -e 'require(\"./index.js\").delete(\"vm-with-apache\", console.log)'", "list": "node -e 'require(\"./index.js\").list(console.log)'" diff --git a/samples/startup-script/system-test/index.test.js b/samples/startup-script/system-test/index.test.js index c53657af..84e21562 100644 --- a/samples/startup-script/system-test/index.test.js +++ b/samples/startup-script/system-test/index.test.js @@ -15,44 +15,48 @@ 'use strict'; -const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); const uuid = require('uuid'); +const assert = require('assert'); const example = require(`../index`); -test.before(tools.checkCredentials); -test.beforeEach(tools.stubConsole); -test.afterEach.always(tools.restoreConsole); -test.cb(`should list vms`, t => { - example.list((err, result) => { - t.ifError(err); - t.truthy(result); - t.true(Array.isArray(result)); - t.end(); +describe('start-up script',() =>{ + before(tools.checkCredentials); + beforeEach(tools.stubConsole); + afterEach(tools.restoreConsole); + + it('should list vms', () => { + example.list((err, result) => { + assert.ifError(err); + assert.ok(result); + assert.strictEqual(Array.isArray(result),true); + }); }); -}); -test.cb(`should create vm`, t => { - const TESTS_PREFIX = 'gcloud-tests-'; - const name = generateName('vm-with-apache'); - - function generateName(customPrefix) { - return [TESTS_PREFIX, customPrefix + '-', uuid.v4().replace('-', '')] - .join('') - .substr(0, 61); - } - - example.create(name, (err, result) => { - t.ifError(err); - t.truthy(result); - - // Clean up newly created vm. - example.delete(name, (err, result) => { - t.ifError(err); - t.truthy(result); - t.end(); + + it('should create vm', () => { + const TESTS_PREFIX = 'gcloud-tests-'; + const name = generateName('vm-with-apache'); + + function generateName(customPrefix) { + return [TESTS_PREFIX, customPrefix + '-', uuid.v4().replace('-', '')] + .join('') + .substr(0, 61); + } + + example.create(name, (err, result) => { + assert.ifError(err); + assert.ok(result); + + // Clean up newly created vm. + example.delete(name, (err, result) => { + assert.ifError(err); + assert.ok(result); + + }); }); }); + }); diff --git a/samples/system-test/vms.test.js b/samples/system-test/vms.test.js index 8a45dd63..64257413 100644 --- a/samples/system-test/vms.test.js +++ b/samples/system-test/vms.test.js @@ -15,20 +15,20 @@ 'use strict'; -const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); +const path = require(`path`); +const assert = require('assert'); -const vmsExample = require(`../vms`); +const cmd = `node vms.js`; +const cwd = path.join(__dirname, `..`); -test.before(tools.checkCredentials); -test.beforeEach(tools.stubConsole); -test.afterEach.always(tools.restoreConsole); +describe('should retrieve list of vms',function(){ + + it('vms_inspect_string', async function() { + const output = await tools.runAsync(cmd,cwd); -test.cb(`should retrieve vms`, t => { - vmsExample.main((err, result) => { - t.ifError(err); - t.truthy(result); - t.true(Array.isArray(result)); - t.end(); - }); -}); + assert.strictEqual(output.includes('VMs:'), true); + + }); + +}); \ No newline at end of file diff --git a/samples/system-test/vms_api.test.js b/samples/system-test/vms_api.test.js index e7b762fd..133a9f89 100644 --- a/samples/system-test/vms_api.test.js +++ b/samples/system-test/vms_api.test.js @@ -15,19 +15,20 @@ 'use strict'; -const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); +const path = require(`path`); +const assert = require('assert'); -const vmsExample = require(`../vms_api`); +const cmd = `node vms_api.js`; +const cwd = path.join(__dirname, `..`); -test.before(tools.checkCredentials); -test.beforeEach(tools.stubConsole); -test.afterEach.always(tools.restoreConsole); +describe('should retrieve list of vms via api',function(){ + + it('vms_api_inspect_string', async function() { + const output = await tools.runAsync(cmd,cwd); -test.cb('should retrieve vms', t => { - vmsExample.main((err, result) => { - t.ifError(err); - t.truthy(result); - t.end(); - }); -}); + assert.strictEqual(output.includes('VMs:'), true); + + }); + +}); \ No newline at end of file diff --git a/samples/test/mailjet.test.js b/samples/test/mailjet.test.js index 38df8086..95ce3013 100644 --- a/samples/test/mailjet.test.js +++ b/samples/test/mailjet.test.js @@ -16,44 +16,49 @@ 'use strict'; const proxyquire = require(`proxyquire`).noPreserveCache(); -const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); +const assert = require('assert'); process.env.MAILJET_API_KEY = `foo`; process.env.MAILJET_API_SECRET = `bar`; -test.beforeEach(tools.stubConsole); -test.afterEach.always(tools.restoreConsole); - -test.cb(`should send an email`, t => { - proxyquire(`../mailjet`, { - nodemailer: { - createTransport: arg => { - t.is(arg, `test`); - return { - sendMail: (payload, cb) => { - t.deepEqual(payload, { - from: `ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM`, - to: `EMAIL@EXAMPLE.COM`, - subject: `test email from Node.js on Google Cloud Platform`, - text: `Hello!\n\nThis a test email from Node.js.`, - }); - cb(null, `done`); - t.end(); +describe('mailjet',() =>{ + + beforeEach(tools.stubConsole); + afterEach(tools.restoreConsole); + + it('should send an email', () => { + proxyquire(`../mailjet`, { + nodemailer: { + createTransport: arg => { + assert.strictEqual(arg, `test`); + return { + sendMail: (payload, cb) => { + assert.deepEqual(payload, { + from: `ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM`, + to: `EMAIL@EXAMPLE.COM`, + subject: `test email from Node.js on Google Cloud Platform`, + text: `Hello!\n\nThis a test email from Node.js.`, + }); + cb(null, `done`); + }, + }; + }, + }, + 'nodemailer-smtp-transport': options => { + assert.deepEqual(options, { + host: `in.mailjet.com`, + port: 2525, + auth: { + user: `foo`, + pass: `bar`, }, - }; + }); + return `test`; }, - }, - 'nodemailer-smtp-transport': options => { - t.deepEqual(options, { - host: `in.mailjet.com`, - port: 2525, - auth: { - user: `foo`, - pass: `bar`, - }, - }); - return `test`; - }, + }); }); + }); + + diff --git a/samples/test/sendgrid.test.js b/samples/test/sendgrid.test.js index a0162036..6e9a3839 100644 --- a/samples/test/sendgrid.test.js +++ b/samples/test/sendgrid.test.js @@ -16,43 +16,49 @@ 'use strict'; const proxyquire = require(`proxyquire`).noPreserveCache(); -const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); +const assert = require('assert'); process.env.SENDGRID_API_KEY = `foo`; -test.beforeEach(tools.stubConsole); -test.afterEach.always(tools.restoreConsole); - -test.cb(`should send an email`, t => { - proxyquire(`../sendgrid`, { - sendgrid: key => { - t.is(key, `foo`); - return { - emptyRequest: x => x, - API: request => { - t.deepEqual(request, { - method: `POST`, - path: `/v3/mail/send`, - body: { - personalizations: [ - { - to: [{email: `to_email@example.com`}], - subject: `Sendgrid test email from Node.js on Google Cloud Platform`, - }, - ], - from: {email: `from_email@example.com`}, - content: [ - { - type: `text/plain`, - value: `Hello!\n\nThis a Sendgrid test email from Node.js on Google Cloud Platform.`, - }, - ], - }, - }); - t.end(); - }, - }; - }, + +describe('sendgrid',() =>{ + + beforeEach(tools.stubConsole); + afterEach(tools.restoreConsole); + + it('should send an email', () => { + proxyquire(`../sendgrid`, { + sendgrid: key => { + assert.strictEqual(key, `foo`); + return { + emptyRequest: x => x, + API: request => { + assert.deepEqual(request, { + method: `POST`, + path: `/v3/mail/send`, + body: { + personalizations: [ + { + to: [{email: `to_email@example.com`}], + subject: `Sendgrid test email from Node.js on Google Cloud Platform`, + }, + ], + from: {email: `from_email@example.com`}, + content: [ + { + type: `text/plain`, + value: `Hello!\n\nThis a Sendgrid test email from Node.js on Google Cloud Platform.`, + }, + ], + }, + }); + + }, + }; + }, + }); }); + }); + From 468f651ce5e0f326f3f12ab0c3a2f7f42b53a27a Mon Sep 17 00:00:00 2001 From: muraliQlogic Date: Thu, 25 Oct 2018 22:25:16 +0530 Subject: [PATCH 2/9] Updated async/await implementation --- samples/mailjet.js | 38 ++-- samples/package.json | 8 +- samples/quickstart.js | 30 ++- samples/sendgrid.js | 52 +++-- samples/startup-script/index.js | 202 +++++++++--------- samples/startup-script/package.json | 6 +- .../startup-script/system-test/index.test.js | 32 +-- samples/system-test/vms.test.js | 13 +- samples/system-test/vms_api.test.js | 13 +- samples/test/mailjet.test.js | 14 +- samples/test/sendgrid.test.js | 9 +- samples/vms.js | 22 +- samples/vms_api.js | 84 +++----- 13 files changed, 234 insertions(+), 289 deletions(-) diff --git a/samples/mailjet.js b/samples/mailjet.js index 800f79a3..3adf5b61 100644 --- a/samples/mailjet.js +++ b/samples/mailjet.js @@ -19,30 +19,26 @@ const mailer = require('nodemailer'); const smtp = require('nodemailer-smtp-transport'); -const transport = mailer.createTransport( - smtp({ - host: 'in.mailjet.com', - port: 2525, - auth: { - user: process.env.MAILJET_API_KEY || '', - }, - }) -); +async function mailjet() { + const transport = mailer.createTransport( + smtp({ + host: 'in.mailjet.com', + port: 2525, + auth: { + user: process.env.MAILJET_API_KEY || '', + }, + }) + ); -transport.sendMail( - { + const json = await transport.sendMail({ from: 'ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM', // From address to: 'EMAIL@EXAMPLE.COM', // To address subject: 'test email from Node.js on Google Cloud Platform', // Subject text: 'Hello!\n\nThis a test email from Node.js.', // Content - }, - function(err, json) { - if (err) { - console.log(err); - } else { - console.log(json); - } - } -); + }); + console.log(json); +} +mailjet().catch(console.error); + // [END send] diff --git a/samples/package.json b/samples/package.json index c0cae987..67795f07 100644 --- a/samples/package.json +++ b/samples/package.json @@ -10,7 +10,7 @@ }, "scripts": { "system-test": "mocha system-test/*.js --timeout 600000", - "startup-test": "ava -T 200s --verbose startup-script/system-test/*.test.js", + "startup-test": "mocha startup-script/system-test/*.test.js --timeout 600000", "test": "npm run system-test && npm run startup-test" }, "dependencies": { @@ -18,10 +18,12 @@ "googleapis": "^34.0.0", "nodemailer": "^4.3.1", "nodemailer-smtp-transport": "^2.7.4", - "sendgrid": "^5.2.3" + "sendgrid": "^5.2.3", + "axios": "^0.18.0" }, "devDependencies": { "@google-cloud/nodejs-repo-tools": "^2.3.1", - "mocha": "^5.0.0" + "mocha": "^5.0.0", + "proxyquire": "^2.0.1" } } diff --git a/samples/quickstart.js b/samples/quickstart.js index ae0ba479..d3ca049e 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -24,20 +24,18 @@ const compute = new Compute(); // Create a new VM using the latest OS image of your choice. const zone = compute.zone('us-central1-a'); -const name = 'ubuntu-http'; - -zone - .createVM(name, {os: 'ubuntu'}) - .then(data => { - // `operation` lets you check the status of long-running tasks. - const vm = data[0]; - const operation = data[1]; - return operation.promise(); - }) - .then(() => { - // Virtual machine created! - }) - .catch(err => { - console.error('ERROR:', err); - }); +const name = 'ubuntu-http1'; + +async function createVM() { + const data = await zone.createVM(name, {os: 'ubuntu'}); + + // `operation` lets you check the status of long-running tasks. + const vm = data[0]; + const operation = data[1]; + // Virtual machine created! + return operation.promise(); +} + +createVM().catch(console.error); + // [END compute_engine_quickstart] diff --git a/samples/sendgrid.js b/samples/sendgrid.js index 63ffad3b..1890224a 100644 --- a/samples/sendgrid.js +++ b/samples/sendgrid.js @@ -19,33 +19,31 @@ const Sendgrid = require('sendgrid')( process.env.SENDGRID_API_KEY || '' ); -const request = Sendgrid.emptyRequest({ - method: 'POST', - path: '/v3/mail/send', - body: { - personalizations: [ - { - to: [{email: 'to_email@example.com'}], - subject: 'Sendgrid test email from Node.js on Google Cloud Platform', - }, - ], - from: {email: 'from_email@example.com'}, - content: [ - { - type: 'text/plain', - value: - 'Hello!\n\nThis a Sendgrid test email from Node.js on Google Cloud Platform.', - }, - ], - }, -}); +async function sendgrid() { + const request = Sendgrid.emptyRequest({ + method: 'POST', + path: '/v3/mail/send', + body: { + personalizations: [ + { + to: [{email: 'to_email@example.com'}], + subject: 'Sendgrid test email from Node.js on Google Cloud Platform', + }, + ], + from: {email: 'from_email@example.com'}, + content: [ + { + type: 'text/plain', + value: + 'Hello!\n\nThis a Sendgrid test email from Node.js on Google Cloud Platform.', + }, + ], + }, + }); -Sendgrid.API(request, function(error, response) { - if (error) { - console.log('Mail not sent; see error message below.'); - } else { - console.log('Mail sent successfully!'); - } + const response = Sendgrid.API(request); console.log(response); -}); +} +sendgrid().catch(console.error); + // [END send] diff --git a/samples/startup-script/index.js b/samples/startup-script/index.js index ad7bf9d2..47a81e92 100644 --- a/samples/startup-script/index.js +++ b/samples/startup-script/index.js @@ -16,26 +16,25 @@ 'use strict'; const Compute = require('@google-cloud/compute'); -const http = require('http'); +const axios = require('axios'); const compute = new Compute(); const zone = compute.zone('us-central1-a'); -// callback(error, externalIp) -function createVm(name, callback) { +async function createVm(name) { // Create a new VM, using default ubuntu image. The startup script // installs apache and a custom homepage. - (async() =>{ - try{ - const config = { - os: 'ubuntu', - http: true, - metadata: { - items: [ - { - key: 'startup-script', - value: `#! /bin/bash + + try { + const config = { + os: 'ubuntu', + http: true, + metadata: { + items: [ + { + key: 'startup-script', + value: `#! /bin/bash # Installs apache and a custom homepage apt-get update @@ -44,106 +43,107 @@ function createVm(name, callback) {

Hello World

This page was created from a simple start-up script!

`, - }, - ], - }, - }; - const vm = zone.vm(name); - - const data = await vm.create(config); - console.log('Creating VM ...'); - await data[1].promise(); - const metadata = await vm.getMetadata(); - - // External IP of the VM. - const ip = metadata[0].networkInterfaces[0].accessConfigs[0].natIP; - console.log(`Booting new VM with IP http://${ip}...`); - - // Ping the VM to determine when the HTTP server is ready. - let waiting = true; - const timer = setInterval( - ip => { - http - .get('http://' + ip, res => { - const statusCode = res.statusCode; - if (statusCode === 200 && waiting) { - waiting = false; - clearTimeout(timer); - // HTTP server is ready. - console.log('Ready!'); - callback(null, ip); - } - }) - .on('error', () => { - // HTTP server is not ready yet. - process.stdout.write('.'); - }); }, - 2000, - ip - ); - - }catch(err){ - callback(err); - } - })(); + ], + }, + }; + const vm = zone.vm(name); + console.log('Creating VM ...'); + const data = await vm.create(config); + await data[1].promise(); + const metadata = await vm.getMetadata(); + + // External IP of the VM. + const ip = metadata[0].networkInterfaces[0].accessConfigs[0].natIP; + console.log(`Booting new VM with IP http://${ip}...`); + // Ping the VM to determine when the HTTP server is ready. + return await pingVM(ip); + } catch (err) { + console.error(`Something went wrong while creating ${name} :`, err); + } +} + +async function pingVM(ip) { + return new Promise(resolve => { + const timer = setInterval( + async ip => { + try { + const res = await axios.get('http://' + ip); + const statusCode = res.status; + if (statusCode === 200) { + // waiting = false; + clearTimeout(timer); + // HTTP server is ready. + console.log('Ready!'); + resolve(ip); + //return Promise.resolve(ip); + } else { + // HTTP server is not ready yet. + process.stdout.write('.'); + } + } catch (err) { + process.stdout.write('.'); + } + }, + 2000, + ip + ); + }); } // List all VMs and their external IPs in a given zone. -// callback(error, [[name, ip], [name, ip], ...]) -function listVms(callback) { - (async () => { - try{ - const data = await zone.getVMs(); - const vms = data[0]; - const results=[]; - for(var i in vms){ - var metadata = await vms[i].getMetadata(); - results.push(metadata); - } - callback( - null, - results.map(data => { - return { - ip: data[0]['networkInterfaces'][0]['accessConfigs'] - ? data[0]['networkInterfaces'][0]['accessConfigs'][0]['natIP'] - : 'no external ip', - name: data[0].name, - }; - }) - ) - } - catch(err){ - callback(err); +async function listVms() { + try { + const data = await zone.getVMs(); + const vms = data[0]; + const results = []; + for (const i in vms) { + const metadata = await vms[i].getMetadata(); + results.push(metadata); } - })(); + + return results.map(data => { + return { + ip: data[0]['networkInterfaces'][0]['accessConfigs'] + ? data[0]['networkInterfaces'][0]['accessConfigs'][0]['natIP'] + : 'no external ip', + name: data[0].name, + }; + }); + } catch (err) { + console.error('Something went wrong while listing VMs :', err); + } } -function deleteVm(name, callback) { - (async () => { - try{ - const vm = zone.vm(name); - const data = await vm.delete() - console.log('Deleting ...'); - await data[0].promise(); - // VM deleted - callback(null, name); - }catch(err){ - callback(err); - } - })(); - +async function deleteVm(name) { + try { + const vm = zone.vm(name); + const data = await vm.delete(); + console.log('Deleting ...'); + await data[0].promise(); + // VM deleted + return name; + } catch (err) { + console.error(`Something went wrong while deleting ${name} :`, err); + } } -exports.create = (name, cb) => { - createVm(name, cb); +exports.create = async name => { + const ip = await createVm(name); + console.log('ip is ' + ip); + console.log(`${name} created succesfully`); + return ip; }; -exports.list = cb => { - listVms(cb); +exports.list = async () => { + const vms = await listVms(); + console.log(vms); + return vms; }; -exports.delete = (name, cb) => { - deleteVm(name, cb); +exports.delete = async name => { + const result = await deleteVm(name); + console.log(`${name} deleted succesfully`); + return result; }; diff --git a/samples/startup-script/package.json b/samples/startup-script/package.json index 888a1d31..1076dc17 100644 --- a/samples/startup-script/package.json +++ b/samples/startup-script/package.json @@ -4,7 +4,11 @@ "description": "Start a Google Compute Engine and run the startup script.", "main": "index.js", "dependencies": { - "@google-cloud/compute": "0.10.0" + "@google-cloud/compute": "0.10.0", + "axios": "^0.18.0" + }, + "engines": { + "node": ">=7.6.0" }, "devDependencies": { "@google-cloud/nodejs-repo-tools": "^2.3.0", diff --git a/samples/startup-script/system-test/index.test.js b/samples/startup-script/system-test/index.test.js index 84e21562..2c2621ac 100644 --- a/samples/startup-script/system-test/index.test.js +++ b/samples/startup-script/system-test/index.test.js @@ -21,22 +21,18 @@ const assert = require('assert'); const example = require(`../index`); - -describe('start-up script',() =>{ +describe('start-up script', async () => { before(tools.checkCredentials); beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); - it('should list vms', () => { - example.list((err, result) => { - assert.ifError(err); - assert.ok(result); - assert.strictEqual(Array.isArray(result),true); - }); + it('should list vms', async () => { + const vms = await example.list(); + assert.ok(vms); + assert.strictEqual(Array.isArray(vms), true); }); - - it('should create vm', () => { + it('should create vm', async () => { const TESTS_PREFIX = 'gcloud-tests-'; const name = generateName('vm-with-apache'); @@ -46,17 +42,9 @@ describe('start-up script',() =>{ .substr(0, 61); } - example.create(name, (err, result) => { - assert.ifError(err); - assert.ok(result); - - // Clean up newly created vm. - example.delete(name, (err, result) => { - assert.ifError(err); - assert.ok(result); - - }); - }); + const ip = await example.create(name); + assert.ok(ip); + const result = await example.delete(name); + assert.strictEqual(result, name); }); - }); diff --git a/samples/system-test/vms.test.js b/samples/system-test/vms.test.js index 64257413..16a53656 100644 --- a/samples/system-test/vms.test.js +++ b/samples/system-test/vms.test.js @@ -22,13 +22,10 @@ const assert = require('assert'); const cmd = `node vms.js`; const cwd = path.join(__dirname, `..`); -describe('should retrieve list of vms',function(){ - +describe('should retrieve list of vms', function() { it('vms_inspect_string', async function() { - const output = await tools.runAsync(cmd,cwd); + const output = await tools.runAsync(cmd, cwd); - assert.strictEqual(output.includes('VMs:'), true); - - }); - -}); \ No newline at end of file + assert.strictEqual(output.includes('VMs:'), true); + }); +}); diff --git a/samples/system-test/vms_api.test.js b/samples/system-test/vms_api.test.js index 133a9f89..026ee149 100644 --- a/samples/system-test/vms_api.test.js +++ b/samples/system-test/vms_api.test.js @@ -22,13 +22,10 @@ const assert = require('assert'); const cmd = `node vms_api.js`; const cwd = path.join(__dirname, `..`); -describe('should retrieve list of vms via api',function(){ - +describe('should retrieve list of vms via api', function() { it('vms_api_inspect_string', async function() { - const output = await tools.runAsync(cmd,cwd); + const output = await tools.runAsync(cmd, cwd); - assert.strictEqual(output.includes('VMs:'), true); - - }); - -}); \ No newline at end of file + assert.strictEqual(output.includes('VMs:'), true); + }); +}); diff --git a/samples/test/mailjet.test.js b/samples/test/mailjet.test.js index 95ce3013..c562e8ae 100644 --- a/samples/test/mailjet.test.js +++ b/samples/test/mailjet.test.js @@ -22,8 +22,7 @@ const assert = require('assert'); process.env.MAILJET_API_KEY = `foo`; process.env.MAILJET_API_SECRET = `bar`; -describe('mailjet',() =>{ - +describe('mailjet', () => { beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); @@ -33,20 +32,20 @@ describe('mailjet',() =>{ createTransport: arg => { assert.strictEqual(arg, `test`); return { - sendMail: (payload, cb) => { - assert.deepEqual(payload, { + sendMail: payload => { + assert.deepStrictEqual(payload, { from: `ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM`, to: `EMAIL@EXAMPLE.COM`, subject: `test email from Node.js on Google Cloud Platform`, text: `Hello!\n\nThis a test email from Node.js.`, }); - cb(null, `done`); + return `done`; }, }; }, }, 'nodemailer-smtp-transport': options => { - assert.deepEqual(options, { + assert.deepStrictEqual(options, { host: `in.mailjet.com`, port: 2525, auth: { @@ -58,7 +57,4 @@ describe('mailjet',() =>{ }, }); }); - }); - - diff --git a/samples/test/sendgrid.test.js b/samples/test/sendgrid.test.js index 6e9a3839..641032ca 100644 --- a/samples/test/sendgrid.test.js +++ b/samples/test/sendgrid.test.js @@ -21,9 +21,7 @@ const assert = require('assert'); process.env.SENDGRID_API_KEY = `foo`; - -describe('sendgrid',() =>{ - +describe('sendgrid', () => { beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); @@ -34,7 +32,7 @@ describe('sendgrid',() =>{ return { emptyRequest: x => x, API: request => { - assert.deepEqual(request, { + assert.deepStrictEqual(request, { method: `POST`, path: `/v3/mail/send`, body: { @@ -53,12 +51,9 @@ describe('sendgrid',() =>{ ], }, }); - }, }; }, }); }); - }); - diff --git a/samples/vms.js b/samples/vms.js index 6188927a..4023f0ad 100644 --- a/samples/vms.js +++ b/samples/vms.js @@ -30,29 +30,23 @@ const compute = new Compute(); // [END initialize] // [START list] -/** - * @param {Function} callback Callback function. - */ -function getVmsExample(callback) { + +async function getVmsExample() { // In this example we only want one VM per page const options = { maxResults: 1, }; - compute.getVMs(options, (err, vms) => { - if (err) { - return callback(err); - } - - console.log('VMs:', vms); - callback(null, vms); - }); + const vms = await compute.getVMs(options); + return vms; } // [END list] // [END complete] // Run the examples -exports.main = cb => { - getVmsExample(cb); +exports.main = async () => { + const vms = await getVmsExample().catch(console.error); + if (vms) console.log('VMs:', vms); + return vms; }; if (module === require.main) { diff --git a/samples/vms_api.js b/samples/vms_api.js index aff335a6..c92b16f1 100644 --- a/samples/vms_api.js +++ b/samples/vms_api.js @@ -22,32 +22,29 @@ const compute = google.compute('v1'); // [END initialize] // [START auth] -function auth(callback) { - google.auth.getApplicationDefault(function(err, authClient) { - if (err) { - return callback(err); - } +async function auth() { + const data = await google.auth.getApplicationDefault(); + let authClient = data.credential; + const projectId = authClient.projectId; - const projectId = authClient.projectId; + // The createScopedRequired method returns true when running on GAE or a + // local developer machine. In that case, the desired scopes must be passed + // in manually. When the code is running in GCE or GAE Flexible, the scopes + // are pulled from the GCE metadata server. + // See https://cloud.google.com/compute/docs/authentication for more + // information. + if (authClient.createScopedRequired && authClient.createScopedRequired()) { + // Scopes can be specified either as an array or as a single, + // space-delimited string. + authClient = authClient.createScoped([ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/compute', + 'https://www.googleapis.com/auth/compute.readonly', + ]); + authClient.projectId = projectId; + } - // The createScopedRequired method returns true when running on GAE or a - // local developer machine. In that case, the desired scopes must be passed - // in manually. When the code is running in GCE or GAE Flexible, the scopes - // are pulled from the GCE metadata server. - // See https://cloud.google.com/compute/docs/authentication for more - // information. - if (authClient.createScopedRequired && authClient.createScopedRequired()) { - // Scopes can be specified either as an array or as a single, - // space-delimited string. - authClient = authClient.createScoped([ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/compute', - 'https://www.googleapis.com/auth/compute.readonly', - ]); - authClient.projectId = projectId; - } - callback(null, authClient); - }); + return authClient; } // [END auth] @@ -55,38 +52,21 @@ function auth(callback) { /** * @param {Function} callback Callback function. */ -function getVmsExample(callback) { - auth(function(err, authClient) { - if (err) { - return callback(err); - } - // Retrieve the vms - compute.instances.aggregatedList( - { - auth: authClient, - project: authClient.projectId, - // In this example we only want one VM per page - maxResults: 1, - }, - function(err, vms) { - if (err) { - return callback(err); - } +async function getVmsExample() { + const authClient = await auth(); - console.log('VMs:', vms); - callback(null, vms); - } - ); + // Retrieve the vms + const vms = await compute.instances.aggregatedList({ + auth: authClient, + project: authClient.projectId, + // In this example we only want one VM per page + maxResults: 1, }); + console.log('VMs:', vms); + return vms; } // [END list] // [END complete] // Run the examples -exports.main = function(cb) { - getVmsExample(cb); -}; - -if (module === require.main) { - exports.main(console.log); -} +getVmsExample().catch(console.error); From 8febb214c8ece6495e738ea35b45883900551b0b Mon Sep 17 00:00:00 2001 From: muraliQlogic Date: Thu, 25 Oct 2018 23:00:37 +0530 Subject: [PATCH 3/9] Fixing linting issue --- samples/startup-script/system-test/.eslintrc.yml | 2 ++ samples/system-test/.eslintrc.yml | 2 ++ samples/test/.eslintrc.yml | 2 ++ 3 files changed, 6 insertions(+) diff --git a/samples/startup-script/system-test/.eslintrc.yml b/samples/startup-script/system-test/.eslintrc.yml index c0289282..75216436 100644 --- a/samples/startup-script/system-test/.eslintrc.yml +++ b/samples/startup-script/system-test/.eslintrc.yml @@ -1,4 +1,6 @@ --- +env: + mocha: true rules: node/no-unpublished-require: off node/no-unsupported-features: off diff --git a/samples/system-test/.eslintrc.yml b/samples/system-test/.eslintrc.yml index c0289282..75216436 100644 --- a/samples/system-test/.eslintrc.yml +++ b/samples/system-test/.eslintrc.yml @@ -1,4 +1,6 @@ --- +env: + mocha: true rules: node/no-unpublished-require: off node/no-unsupported-features: off diff --git a/samples/test/.eslintrc.yml b/samples/test/.eslintrc.yml index 43b4c19e..2385deb8 100644 --- a/samples/test/.eslintrc.yml +++ b/samples/test/.eslintrc.yml @@ -1,4 +1,6 @@ --- +env: + mocha: true rules: node/no-unpublished-require: off node/no-unsupported-features: off From 505aec893caf791c2be68e0465ca40c127a5fda0 Mon Sep 17 00:00:00 2001 From: muraliQlogic Date: Sun, 28 Oct 2018 18:58:53 +0530 Subject: [PATCH 4/9] Changes as per review comment --- samples/package.json | 3 +- samples/quickstart.js | 7 ++-- samples/sendgrid.js | 2 +- samples/startup-script/index.js | 61 ++++++++++++++------------------- 4 files changed, 32 insertions(+), 41 deletions(-) diff --git a/samples/package.json b/samples/package.json index 67795f07..efb2a76d 100644 --- a/samples/package.json +++ b/samples/package.json @@ -19,7 +19,8 @@ "nodemailer": "^4.3.1", "nodemailer-smtp-transport": "^2.7.4", "sendgrid": "^5.2.3", - "axios": "^0.18.0" + "axios": "^0.18.0", + "uuid": "^3.2.1" }, "devDependencies": { "@google-cloud/nodejs-repo-tools": "^2.3.1", diff --git a/samples/quickstart.js b/samples/quickstart.js index d3ca049e..a65c414f 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -18,13 +18,13 @@ // [START compute_engine_quickstart] // Imports the Google Cloud client library const Compute = require('@google-cloud/compute'); - +const uuid = require('uuid'); // Creates a client const compute = new Compute(); // Create a new VM using the latest OS image of your choice. const zone = compute.zone('us-central1-a'); -const name = 'ubuntu-http1'; +const name = `ubuntu-http-${uuid().split('-')[0]}`; async function createVM() { const data = await zone.createVM(name, {os: 'ubuntu'}); @@ -32,8 +32,9 @@ async function createVM() { // `operation` lets you check the status of long-running tasks. const vm = data[0]; const operation = data[1]; + + await operation.promise(); // Virtual machine created! - return operation.promise(); } createVM().catch(console.error); diff --git a/samples/sendgrid.js b/samples/sendgrid.js index 1890224a..20137857 100644 --- a/samples/sendgrid.js +++ b/samples/sendgrid.js @@ -41,7 +41,7 @@ async function sendgrid() { }, }); - const response = Sendgrid.API(request); + const response = await Sendgrid.API(request); console.log(response); } sendgrid().catch(console.error); diff --git a/samples/startup-script/index.js b/samples/startup-script/index.js index 47a81e92..748b9c11 100644 --- a/samples/startup-script/index.js +++ b/samples/startup-script/index.js @@ -47,62 +47,52 @@ async function createVm(name) { ], }, }; - const vm = zone.vm(name); + const vmObj = zone.vm(name); console.log('Creating VM ...'); - const data = await vm.create(config); - await data[1].promise(); - const metadata = await vm.getMetadata(); + const [vm, operation] = await vmObj.create(config); + await operation.promise(); + const [metadata] = await vm.getMetadata(); // External IP of the VM. - const ip = metadata[0].networkInterfaces[0].accessConfigs[0].natIP; + const ip = metadata.networkInterfaces[0].accessConfigs[0].natIP; console.log(`Booting new VM with IP http://${ip}...`); // Ping the VM to determine when the HTTP server is ready. - return await pingVM(ip); + await pingVM(ip); + return ip; } catch (err) { console.error(`Something went wrong while creating ${name} :`, err); } } async function pingVM(ip) { - return new Promise(resolve => { - const timer = setInterval( - async ip => { - try { - const res = await axios.get('http://' + ip); - const statusCode = res.status; - if (statusCode === 200) { - // waiting = false; - clearTimeout(timer); - // HTTP server is ready. - console.log('Ready!'); - resolve(ip); - //return Promise.resolve(ip); - } else { - // HTTP server is not ready yet. - process.stdout.write('.'); - } - } catch (err) { - process.stdout.write('.'); - } - }, - 2000, - ip - ); - }); + let waiting = true; + while (waiting) { + await new Promise(r => setTimeout(r, 2000)); + try { + const res = await axios.get(`http://${ip}`); + const statusCode = res.status; + if (statusCode === 200) { + waiting = false; + console.log('Ready!'); + return; + } else { + process.stdout.write('.'); + } + } catch (err) { + process.stdout.write('.'); + } + } } - // List all VMs and their external IPs in a given zone. async function listVms() { try { - const data = await zone.getVMs(); - const vms = data[0]; + const [vms] = await zone.getVMs(); const results = []; for (const i in vms) { const metadata = await vms[i].getMetadata(); results.push(metadata); } - return results.map(data => { return { ip: data[0]['networkInterfaces'][0]['accessConfigs'] @@ -131,7 +121,6 @@ async function deleteVm(name) { exports.create = async name => { const ip = await createVm(name); - console.log('ip is ' + ip); console.log(`${name} created succesfully`); return ip; }; From cd08ff00299500278a1817b96baab2a2dd5cb2e0 Mon Sep 17 00:00:00 2001 From: muraliQlogic Date: Tue, 30 Oct 2018 01:03:18 +0530 Subject: [PATCH 5/9] Changes as per review comment --- samples/startup-script/index.js | 90 ++++++++++++----------------- samples/startup-script/package.json | 2 +- 2 files changed, 39 insertions(+), 53 deletions(-) diff --git a/samples/startup-script/index.js b/samples/startup-script/index.js index 748b9c11..98eeaa59 100644 --- a/samples/startup-script/index.js +++ b/samples/startup-script/index.js @@ -26,15 +26,14 @@ async function createVm(name) { // Create a new VM, using default ubuntu image. The startup script // installs apache and a custom homepage. - try { - const config = { - os: 'ubuntu', - http: true, - metadata: { - items: [ - { - key: 'startup-script', - value: `#! /bin/bash + const config = { + os: 'ubuntu', + http: true, + metadata: { + items: [ + { + key: 'startup-script', + value: `#! /bin/bash # Installs apache and a custom homepage apt-get update @@ -43,26 +42,23 @@ async function createVm(name) {

Hello World

This page was created from a simple start-up script!

`, - }, - ], - }, - }; - const vmObj = zone.vm(name); - console.log('Creating VM ...'); - const [vm, operation] = await vmObj.create(config); - await operation.promise(); - const [metadata] = await vm.getMetadata(); + }, + ], + }, + }; + const vmObj = zone.vm(name); + console.log('Creating VM ...'); + const [vm, operation] = await vmObj.create(config); + await operation.promise(); + const [metadata] = await vm.getMetadata(); - // External IP of the VM. - const ip = metadata.networkInterfaces[0].accessConfigs[0].natIP; - console.log(`Booting new VM with IP http://${ip}...`); + // External IP of the VM. + const ip = metadata.networkInterfaces[0].accessConfigs[0].natIP; + console.log(`Booting new VM with IP http://${ip}...`); - // Ping the VM to determine when the HTTP server is ready. - await pingVM(ip); - return ip; - } catch (err) { - console.error(`Something went wrong while creating ${name} :`, err); - } + // Ping the VM to determine when the HTTP server is ready. + await pingVM(ip); + return ip; } async function pingVM(ip) { @@ -86,37 +82,27 @@ async function pingVM(ip) { } // List all VMs and their external IPs in a given zone. async function listVms() { - try { - const [vms] = await zone.getVMs(); - const results = []; - for (const i in vms) { - const metadata = await vms[i].getMetadata(); - results.push(metadata); - } - return results.map(data => { + const [vms] = await zone.getVMs(); + return await Promise.all( + vms.map(async vm => { + const [metadata] = await vm.getMetadata(); return { - ip: data[0]['networkInterfaces'][0]['accessConfigs'] - ? data[0]['networkInterfaces'][0]['accessConfigs'][0]['natIP'] + ip: metadata['networkInterfaces'][0]['accessConfigs'] + ? metadata['networkInterfaces'][0]['accessConfigs'][0]['natIP'] : 'no external ip', - name: data[0].name, + name: metadata.name, }; - }); - } catch (err) { - console.error('Something went wrong while listing VMs :', err); - } + }) + ); } async function deleteVm(name) { - try { - const vm = zone.vm(name); - const data = await vm.delete(); - console.log('Deleting ...'); - await data[0].promise(); - // VM deleted - return name; - } catch (err) { - console.error(`Something went wrong while deleting ${name} :`, err); - } + const vm = zone.vm(name); + console.log('Deleting ...'); + const [operation] = await vm.delete(); + await operation.promise(); + // VM deleted + return name; } exports.create = async name => { diff --git a/samples/startup-script/package.json b/samples/startup-script/package.json index 1076dc17..9fe1d803 100644 --- a/samples/startup-script/package.json +++ b/samples/startup-script/package.json @@ -8,7 +8,7 @@ "axios": "^0.18.0" }, "engines": { - "node": ">=7.6.0" + "node": ">=8" }, "devDependencies": { "@google-cloud/nodejs-repo-tools": "^2.3.0", From a654bd92c5bd8a841345d8dd64b41de0a075dbb3 Mon Sep 17 00:00:00 2001 From: muraliQlogic Date: Tue, 30 Oct 2018 01:48:41 +0530 Subject: [PATCH 6/9] Fix for failing samples test --- .../startup-script/system-test/index.test.js | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/samples/startup-script/system-test/index.test.js b/samples/startup-script/system-test/index.test.js index 2c2621ac..82410632 100644 --- a/samples/startup-script/system-test/index.test.js +++ b/samples/startup-script/system-test/index.test.js @@ -26,24 +26,24 @@ describe('start-up script', async () => { beforeEach(tools.stubConsole); afterEach(tools.restoreConsole); + const TESTS_PREFIX = 'gcloud-tests-'; + const name = generateName('vm-with-apache'); + + function generateName(customPrefix) { + return [TESTS_PREFIX, customPrefix + '-', uuid.v4().replace('-', '')] + .join('') + .substr(0, 61); + } + it('should create vm', async () => { + const ip = await example.create(name); + assert.ok(ip); + }); it('should list vms', async () => { const vms = await example.list(); assert.ok(vms); assert.strictEqual(Array.isArray(vms), true); }); - - it('should create vm', async () => { - const TESTS_PREFIX = 'gcloud-tests-'; - const name = generateName('vm-with-apache'); - - function generateName(customPrefix) { - return [TESTS_PREFIX, customPrefix + '-', uuid.v4().replace('-', '')] - .join('') - .substr(0, 61); - } - - const ip = await example.create(name); - assert.ok(ip); + it('should delete vm', async () => { const result = await example.delete(name); assert.strictEqual(result, name); }); From 3a97ffdbc702f994cf976b2bf4efeb450214fc3b Mon Sep 17 00:00:00 2001 From: muraliQlogic Date: Tue, 30 Oct 2018 16:35:21 +0530 Subject: [PATCH 7/9] Changes to use node-fetch and remove axios --- samples/package.json | 2 +- samples/startup-script/index.js | 4 ++-- samples/startup-script/package.json | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/package.json b/samples/package.json index efb2a76d..c3901c25 100644 --- a/samples/package.json +++ b/samples/package.json @@ -16,10 +16,10 @@ "dependencies": { "@google-cloud/compute": "^0.10.0", "googleapis": "^34.0.0", + "node-fetch": "^2.2.0", "nodemailer": "^4.3.1", "nodemailer-smtp-transport": "^2.7.4", "sendgrid": "^5.2.3", - "axios": "^0.18.0", "uuid": "^3.2.1" }, "devDependencies": { diff --git a/samples/startup-script/index.js b/samples/startup-script/index.js index 98eeaa59..b3b9e283 100644 --- a/samples/startup-script/index.js +++ b/samples/startup-script/index.js @@ -16,7 +16,7 @@ 'use strict'; const Compute = require('@google-cloud/compute'); -const axios = require('axios'); +const fetch = require('node-fetch'); const compute = new Compute(); @@ -66,7 +66,7 @@ async function pingVM(ip) { while (waiting) { await new Promise(r => setTimeout(r, 2000)); try { - const res = await axios.get(`http://${ip}`); + const res = await fetch(`http://${ip}`); const statusCode = res.status; if (statusCode === 200) { waiting = false; diff --git a/samples/startup-script/package.json b/samples/startup-script/package.json index 9fe1d803..6ba8aace 100644 --- a/samples/startup-script/package.json +++ b/samples/startup-script/package.json @@ -5,7 +5,7 @@ "main": "index.js", "dependencies": { "@google-cloud/compute": "0.10.0", - "axios": "^0.18.0" + "node-fetch": "^2.2.0" }, "engines": { "node": ">=8" From 666a4f5d8e6ea1ff2ad239ca28dae7f892849971 Mon Sep 17 00:00:00 2001 From: muraliQlogic Date: Sat, 3 Nov 2018 17:37:01 +0530 Subject: [PATCH 8/9] test without node-fetch --- samples/startup-script/index.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/samples/startup-script/index.js b/samples/startup-script/index.js index b3b9e283..46e05ab6 100644 --- a/samples/startup-script/index.js +++ b/samples/startup-script/index.js @@ -16,7 +16,7 @@ 'use strict'; const Compute = require('@google-cloud/compute'); -const fetch = require('node-fetch'); +//const fetch = require('node-fetch'); const compute = new Compute(); @@ -64,8 +64,9 @@ async function createVm(name) { async function pingVM(ip) { let waiting = true; while (waiting) { - await new Promise(r => setTimeout(r, 2000)); - try { + await new Promise(r => setTimeout(r, 500000)); + waiting = false; + /* try { const res = await fetch(`http://${ip}`); const statusCode = res.status; if (statusCode === 200) { @@ -77,7 +78,7 @@ async function pingVM(ip) { } } catch (err) { process.stdout.write('.'); - } + }*/ } } // List all VMs and their external IPs in a given zone. From d5a376e6c70a687d9e980ef156ceaf2c1268f85b Mon Sep 17 00:00:00 2001 From: muraliQlogic Date: Sat, 3 Nov 2018 18:21:29 +0530 Subject: [PATCH 9/9] reinstate --- samples/startup-script/index.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/samples/startup-script/index.js b/samples/startup-script/index.js index 46e05ab6..b3b9e283 100644 --- a/samples/startup-script/index.js +++ b/samples/startup-script/index.js @@ -16,7 +16,7 @@ 'use strict'; const Compute = require('@google-cloud/compute'); -//const fetch = require('node-fetch'); +const fetch = require('node-fetch'); const compute = new Compute(); @@ -64,9 +64,8 @@ async function createVm(name) { async function pingVM(ip) { let waiting = true; while (waiting) { - await new Promise(r => setTimeout(r, 500000)); - waiting = false; - /* try { + await new Promise(r => setTimeout(r, 2000)); + try { const res = await fetch(`http://${ip}`); const statusCode = res.status; if (statusCode === 200) { @@ -78,7 +77,7 @@ async function pingVM(ip) { } } catch (err) { process.stdout.write('.'); - }*/ + } } } // List all VMs and their external IPs in a given zone.