Skip to content

Commit

Permalink
adding browserify client example
Browse files Browse the repository at this point in the history
  • Loading branch information
nfriedly committed Jul 27, 2016
1 parent 32a67c2 commit fd5e8c4
Show file tree
Hide file tree
Showing 8 changed files with 156 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ jsdoc/
doc/
coverage/
dist/
node_modules/
examples/**/node_modules/
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ test/resources/tts-output.ogg
doc/
.vscode/
dist/
.env
examples/browserify/node_modules/

25 changes: 25 additions & 0 deletions examples/browserify/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Watson Developer Cloud Browserify Example

This example app shows a basic client and server setup to use the Watson JS SDK in a client-side context.

The example here uses [express](http://expressjs.com/) to serve the content and
[express-browserify](https://www.npmjs.com/package/express-browserify) to generate the client-side bundle.

## Important notes

A server-side component is required to generate auth tokens for services that use a username/password combo.
(This is all services except Alchemy and Visual Recognition which use API keys instead.)

Not all Watson services currently support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS),
and in some cases, certain methods work while others do not. Below is a partial list of service support:

The following services support CORS

* Tradeoff Analytics
* Tone Analyzer
* Speech to Text
* Text to Speech

The following services do not support CORS

* Language Translator
17 changes: 17 additions & 0 deletions examples/browserify/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "watson-developer-cloud-browserify-example",
"version": "1.0.0",
"description": "Use the Watson JS SDK in browsers via browserify",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "Apache-2.0",
"dependencies": {
"dotenv": "^2.0.0",
"express": "^4.14.0",
"express-browserify": "^1.0.2"
},
"devDependencies": {}
}
5 changes: 5 additions & 0 deletions examples/browserify/public/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"env": {
"browser": true
}
}
42 changes: 42 additions & 0 deletions examples/browserify/public/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// notes:
//
// * This file is bundled by exprss-browserify into bundle.js
//
// * The require('watson-developer-cloud/language_translator/v2') could also be written as require('watson-developer-cloud').LanguageTranslatorV2,
// but that version results in a much larger bundle size.
//
// * Tokens expire after 1 hour. This demo simply fetches a new one for each translation rather than keeping a fresh one.
//
// * fetch() is a modern version of XMLHttpRequest. A pollyfill is available for older browsers: https://github.com/github/fetch

var ToneAnalyzerV3 = require('watson-developer-cloud/tone_analyzer/v3');

var btn = document.getElementById('analyze-btn');
var input = document.getElementById('input');
var output = document.getElementById('output');

/**
* @return {Promise<String>} returns a promise that resolves to a string token
*/
function getToken() {
return fetch('/api/token/tone_analyzer').then(function(response) {
return response.text();
})
}

function analyze(token) {
var toneAnalyzer = new ToneAnalyzerV3({token: token, version_date:'2016-05-19'});
toneAnalyzer.tone({
text: input.value
}, function(err, result) {
if (err) {
output.innerHTML = err;
return console.log(err);
}
output.innerHTML = JSON.stringify(result, null, 2);
});
}

btn.onclick = function() {
getToken().then(analyze);
};
26 changes: 24 additions & 2 deletions examples/browserify/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,31 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$Title$</title>
<title>Browserify Example | Watson developer Cloud JS SDK </title>
<style type=text/css>
textarea {
height: auto;
min-height: 300px;
width: 100%;
max-width: 800px;
}
</style>
</head>
<body>
$END$

<h1>Browserify Example</h1>
<h2>Watson developer Cloud JS SDK</h2>

<p>This example connects directly from your browser to the Watson Tone Analyzer service (after fetching an auth token from the node.js server.)</p>

<p>Input text:</p>
<textarea id="input">Greetings from IBM Watson!</textarea>

<p><button id="analyze-btn">Analyze</button></p>

<p>Result:</p>
<pre><code id="output"></code></pre>

<script src="/bundle.js"></script>
</body>
</html>
38 changes: 38 additions & 0 deletions examples/browserify/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
var express = require('express');
var app = express();
var expressBrowserify = require('express-browserify');
var dotenv = require('dotenv');
var watson = require('watson-developer-cloud');

var isDev = app.get('env') === 'development';
app.get('/bundle.js', expressBrowserify('public/client.js', {
watch: isDev,
debug: isDev
}));

app.use(express.static('public/'));

// optional: load environment properties from a .env file
dotenv.load({silent: true});

// For local development, specify the username and password or set env properties
var ltAuthService = new watson.AuthorizationV1({
username: process.env.TONE_ANALYZER_USERNAME || '<username>',
password: process.env.TONE_ANALYZER_PASSWORD || '<password>',
url: watson.ToneAnalyzerV3.URL
});

app.get('/api/token/tone_analyzer', function(req, res) {
ltAuthService.getToken(function(err, token) {
if (err) {
console.log('Error retrieving token: ', err);
return res.status(500).send('Error retrieving token');
}
res.send(token);
});
});

var port = process.env.PORT || process.env.VCAP_APP_PORT || 3000;
app.listen(port, function() {
console.log('Watson browserify example server running at http://localhost:%s/', port);
});

0 comments on commit fd5e8c4

Please sign in to comment.