Skip to content

Commit

Permalink
docs(samples): update samples to use async/await and mocha (#183)
Browse files Browse the repository at this point in the history
  • Loading branch information
muraliQlogic authored and Ace Nassri committed Nov 21, 2022
1 parent eb77011 commit b9c3f6a
Show file tree
Hide file tree
Showing 16 changed files with 287 additions and 340 deletions.
38 changes: 17 additions & 21 deletions compute/mailjet.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 || '<your-mailjet-api-key',
pass: process.env.MAILJET_API_SECRET || '<your-mailjet-api-secret>',
},
})
);
async function mailjet() {
const transport = mailer.createTransport(
smtp({
host: 'in.mailjet.com',
port: 2525,
auth: {
user: process.env.MAILJET_API_KEY || '<your-mailjet-api-key',
pass: process.env.MAILJET_API_SECRET || '<your-mailjet-api-secret>',
},
})
);

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]
10 changes: 6 additions & 4 deletions compute/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,22 @@
"node": ">=8"
},
"scripts": {
"system-test": "ava -T 20s --verbose system-test/*.test.js",
"startup-test": "ava -T 200s --verbose startup-script/system-test/*.test.js",
"system-test": "mocha system-test/*.js --timeout 600000",
"startup-test": "mocha startup-script/system-test/*.test.js --timeout 600000",
"test": "npm run system-test && npm run startup-test"
},
"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"
"sendgrid": "^5.2.3",
"uuid": "^3.2.1"
},
"devDependencies": {
"@google-cloud/nodejs-repo-tools": "^2.3.1",
"ava": "^0.25.0",
"mocha": "^5.0.0",
"proxyquire": "^2.0.1"
}
}
33 changes: 16 additions & 17 deletions compute/quickstart.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,25 @@
// [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-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-http-${uuid().split('-')[0]}`;

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];

await operation.promise();
// Virtual machine created!
}

createVM().catch(console.error);

// [END compute_engine_quickstart]
52 changes: 25 additions & 27 deletions compute/sendgrid.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,33 +19,31 @@ const Sendgrid = require('sendgrid')(
process.env.SENDGRID_API_KEY || '<your-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 = await Sendgrid.API(request);
console.log(response);
});
}
sendgrid().catch(console.error);

// [END send]
163 changes: 71 additions & 92 deletions compute/startup-script/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@
'use strict';

const Compute = require('@google-cloud/compute');
const http = require('http');
const fetch = require('node-fetch');

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.

const config = {
os: 'ubuntu',
http: true,
Expand All @@ -34,112 +34,91 @@ function createVm(name, callback) {
{
key: 'startup-script',
value: `#! /bin/bash
# Installs apache and a custom homepage
apt-get update
apt-get install -y apache2
cat <<EOF > /var/www/html/index.html
<!doctype html>
<h1>Hello World</h1>
<p>This page was created from a simple start-up script!</p>`,
# Installs apache and a custom homepage
apt-get update
apt-get install -y apache2
cat <<EOF > /var/www/html/index.html
<!doctype html>
<h1>Hello World</h1>
<p>This page was created from a simple start-up script!</p>`,
},
],
},
};
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 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];

// 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.
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));
// Ping the VM to determine when the HTTP server is ready.
await pingVM(ip);
return ip;
}

async function pingVM(ip) {
let waiting = true;
while (waiting) {
await new Promise(r => setTimeout(r, 2000));
try {
const res = await fetch(`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.
// callback(error, [[name, ip], [name, ip], ...])
function listVms(callback) {
zone
.getVMs()
.then(data => {
const vms = data[0];
const results = vms.map(vm => vm.getMetadata());
return Promise.all(results);
async function listVms() {
const [vms] = await zone.getVMs();
return await Promise.all(
vms.map(async vm => {
const [metadata] = await vm.getMetadata();
return {
ip: metadata['networkInterfaces'][0]['accessConfigs']
? metadata['networkInterfaces'][0]['accessConfigs'][0]['natIP']
: 'no external ip',
name: metadata.name,
};
})
.then(res =>
callback(
null,
res.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));
);
}

function deleteVm(name, callback) {
async function deleteVm(name) {
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));
console.log('Deleting ...');
const [operation] = await vm.delete();
await operation.promise();
// VM deleted
return name;
}

exports.create = (name, cb) => {
createVm(name, cb);
exports.create = async name => {
const ip = await createVm(name);
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;
};
Loading

0 comments on commit b9c3f6a

Please sign in to comment.