Skip to content

Commit

Permalink
Update functions to Async/Await
Browse files Browse the repository at this point in the history
Description:
 Made helper functions to return Promises,
 Removed callbacks from function signatures.
 Updated main to follow async/await construct
  • Loading branch information
kevingrozav committed Sep 8, 2017
1 parent 56b55f0 commit fda7a75
Show file tree
Hide file tree
Showing 4 changed files with 136 additions and 128 deletions.
25 changes: 19 additions & 6 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
{
"compact": false,
"presets": ["es2015"],
"auxiliaryCommentBefore": "istanbul ignore next",
"sourceMaps": "inline"
}
{
"presets": [
["env", {
"targets": {
"node": "0.12"
}
}]
],
"compact": false,
"sourceMaps": "inline",
"plugins": [
"transform-async-to-bluebird",
"transform-promise-to-bluebird",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
7 changes: 4 additions & 3 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ globals:
spy: true
stub: true

parserOptions:
sourceType: "module"
parserOptions:
sourceType: "module"
ecmaVersion: 8

rules:
rules:
# ERRORS
space-before-blocks: 2
indent: [2, 2, { "SwitchCase": 1 }]
Expand Down
13 changes: 9 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,21 @@
"dependencies": {
"babel-preset-es2015": "^6.6.0",
"debug": "^2.2.0",
"request": "^2.73.0"
"request": "^2.73.0",
"babel-preset-env": "^1.5.1",
"bluebird": "^3.5.0"
},
"devDependencies": {
"babel-cli": "^6.10.1",
"chai": "^3.5.0",
"eslint": "^3.3.0",
"mocha": "^2.5.3"
"mocha": "^2.5.3",
"babel-cli": "^6.24.1",
"babel-plugin-transform-async-to-bluebird": "^1.1.1",
"babel-plugin-transform-promise-to-bluebird": "^1.1.1",
"babel-plugin-transform-runtime": "^6.23.0"
},
"engines": {
"node": ">=6.9.1",
"npm": ">=3.10.8"
}
}
}
219 changes: 104 additions & 115 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,135 +10,125 @@ import debug from 'debug';
// Debug log
const log = debug('watsonwork-helloworld-app');

// Return the list of spaces the app belongs to
const spaces = (tok, cb) => {
request.post('https://api.watsonwork.ibm.com/graphql', {
headers: {
jwt: tok,
'Content-Type': 'application/graphql'
},

// This is a GraphQL query, used to retrieve the list of spaces
// visible to the app (given the app OAuth token)
body: `
query {
spaces (first: 50) {
items {
title
id
// Return a list of spaces the app belongs to
const spaces = (tok) => {
return new Promise((resolve, reject) => {
request.post('https://api.watsonwork.ibm.com/graphql', {
headers: {
jwt: tok,
'Content-Type': 'application/graphql'
},
// This is a GraphQL query, used to retrieve the list of spaces
// visible to the app (given the app OAuth token)
body: `
query {
spaces (first: 50) {
items {
title
id
}
}
}
}`
}, (err, res) => {
if(err || res.statusCode !== 200) {
log('Error retrieving spaces %o', err || res.statusCode);
cb(err || new Error(res.statusCode));
return;
}

// Return the list of spaces
const body = JSON.parse(res.body);
log('Space query result %o', body.data.spaces.items);
cb(null, body.data.spaces.items);
}`
}, (err, res) => {
if (err || res.statusCode !== 200) {
log('Error retrieving spaces %o', err || res.statusCode);
return reject(err || new Error(res.statusCode));
}
const body = JSON.parse(res.body);
log('Space query result %o', body.data.spaces.items);

// Return the list of spaces
return resolve(body.data.spaces.items);
});
});
};

// Return an OAuth token for the app
const token = (appId, secret, cb) => {
request.post('https://api.watsonwork.ibm.com/oauth/token', {
auth: {
user: appId,
pass: secret
},
json: true,
form: {
grant_type: 'client_credentials'
}
}, (err, res) => {
if(err || res.statusCode !== 200) {
log('Error getting OAuth token %o', err || res.statusCode);
cb(err || new Error(res.statusCode));
return;
}
cb(null, res.body.access_token);
});
};

// Send an app message to the conversation in a space
const send = (spaceId, text, tok, cb) => {
request.post(
'https://api.watsonwork.ibm.com/v1/spaces/' + spaceId + '/messages', {
headers: {
Authorization: 'Bearer ' + tok
const token = (appId, secret) => {
return new Promise((resolve, reject) => {
request.post('https://api.watsonwork.ibm.com/oauth/token', {
auth: {
user: appId,
pass: secret
},
json: true,
// An App message can specify a color, a title, markdown text and
// an 'actor' useful to show where the message is coming from
body: {
type: 'appMessage',
version: 1.0,
annotations: [{
type: 'generic',
version: 1.0,

color: '#6CB7FB',
title: 'Sample Message',
text: text,

actor: {
name: 'Sample helloworld app'
}
}]
form: {
grant_type: 'client_credentials'
}
}, (err, res) => {
if(err || res.statusCode !== 201) {
log('Error sending message %o', err || res.statusCode);
cb(err || new Error(res.statusCode));
return;
}
log('Send result %d, %o', res.statusCode, res.body);
cb(null, res.body);
if(err || res.statusCode !== 200) {
log('Error getting OAuth token %o', err || res.statusCode);
return reject(err || new Error(res.statusCode));
}
return resolve(res.body.access_token);
});
});
};


// Send an app message to the conversation in a space
const send = (spaceId, text, tok) => {
return new Promise((resolve, reject) => {
request.post(
'https://api.watsonwork.ibm.com/v1/spaces/' + spaceId + '/messages', {
headers: {
Authorization: 'Bearer ' + tok
},
json: true,
// An App message can specify a color, a title, markdown text and
// an 'actor' useful to show where the message is coming from
body: {
type: 'appMessage',
version: 1.0,
annotations: [{
type: 'generic',
version: 1.0,

color: '#6CB7FB',
title: 'Sample Message',
text: text,

actor: {
name: 'Sample helloworld app'
}
}]
}
}, (err, res) => {
if (err || res.statusCode !== 201) {
log('Error sending message %o', err || res.statusCode);
return reject(err || new Error(res.statusCode));
}
log('Send result %d, %o', res.statusCode, res.body);
return resolve(res.body);
});
});
};


// Main app entry point
// Send a message to the conversation in the space matching the given name
export const main = (name, text, appId, secret, cb) => {
// Get an OAuth token for the app
token(appId, secret, (err, tok) => {
if(err) {
cb(err);
export const main = async (name, text, appId, secret, cb) => {
try {
// Get an OAuth token for the app
var tok = await token(appId, secret);
// List the spaces the app belongs to
var spaceList = await spaces(tok);
// Find a space matching the given name
const space = spaceList.filter((s) => s.title === name)[0];
if (!space) {
cb(new Error('Space not found'));
return;
}

// List the spaces the app belongs to
spaces(tok, (err, slist) => {
if(err) {
cb(err);
return;
}

// Find a space matching the given name
const space = slist.filter((s) => s.title === name)[0];
if(!space) {
cb(new Error('Space not found'));
return;
}

// Send the message
log('Sending \'%s\' to space %s', text, space.title);
send(space.id,
text || 'Hello World! Welcome to **Watson Work**!',
tok, (err, res) => {
if(err) {
cb(err);
return;
}
log('Sent message to space %s', space.title);
cb(null);
});
});
});
log('Sending \'%s\' to space %s', text, space.title);
// Send the message
await send(space.id,
text || 'Hello World! Welcome to **Watson Work**!',
tok);
log('Sent message to space %s', space.title);
cb(null);
} catch(err) {
cb(err);
}
};

if(require.main === module)
Expand All @@ -149,5 +139,4 @@ if(require.main === module)
(err) => {
if(err)
console.log('Error sending message:', err);
});

});

0 comments on commit fda7a75

Please sign in to comment.