Skip to content

Commit

Permalink
docs: update examples to use modern JS
Browse files Browse the repository at this point in the history
  • Loading branch information
dbushong committed Oct 25, 2018
1 parent 6cced2e commit 7296fe7
Show file tree
Hide file tree
Showing 4 changed files with 120 additions and 137 deletions.
1 change: 1 addition & 0 deletions examples/.eslintrc
@@ -0,0 +1 @@
{ "extends": "groupon/node8" }
34 changes: 17 additions & 17 deletions examples/browser/browser.js
@@ -1,39 +1,39 @@
'use strict';
require('whatwg-fetch'); // polyfill for fetch, required by gofer
var Gofer = require('gofer');

var rawResponse = document.createElement('pre');
/* eslint-env browser */

const Gofer = require('gofer');

const rawResponse = document.createElement('pre');
rawResponse.innerText = '(loading)';
document.body.appendChild(rawResponse);

function EchoClient(config) {
Gofer.call(this, config, 'echo', '0.0.0');
}
EchoClient.prototype = Object.create(Gofer.prototype);
class EchoClient extends Gofer {
constructor(config) {
super(config, 'echo', '0.0.0');
}

EchoClient.prototype.registerEndpoints({
echo: function withFetch(fetch) {
return function getEcho(qs) {
return fetch('/', { qs: qs }).json();
};
},
});
echo(qs) {
return this.fetch('/', { qs, endpointName: 'echo' }).json();
}
}

function onEchoResponse(data) {
rawResponse.innerText = JSON.stringify(data, null, 2);
}

function onEchoError(error) {
rawResponse.innerText = error.message + '\n\n' + error.stack;
rawResponse.innerText = `${error.message}\n\n${error.stack}`;
}

var echo = new EchoClient({
const echo = new EchoClient({
echo: {
baseUrl: '/echo',
qs: { fromConfig: 'foo' },
},
});

echo.echo({ fromCall: 'mergedIn' })
echo
.echo({ fromCall: 'mergedIn' })
.then(onEchoResponse)
.catch(onEchoError);
33 changes: 17 additions & 16 deletions examples/browser/server.js
@@ -1,23 +1,26 @@
'use strict';
var fs = require('fs');
var http = require('http');

var browserify = require('browserify');
const fs = require('fs');
const http = require('http');

var BASE_HTML = __dirname + '/base.html';
const browserify = require('browserify');

const BASE_HTML = `${__dirname}/base.html`;

function onRequest(req, res) {
if (req.url === '/favicon.ico') {
return res.end('ok');
return void res.end('ok');
}

if (req.url.indexOf('/echo') === 0) {
res.setHeader('Content-Type', 'application/json; charset=utf8');
return res.end(JSON.stringify({
method: req.method,
headers: req.headers,
url: req.url,
}));
return void res.end(
JSON.stringify({
method: req.method,
headers: req.headers,
url: req.url,
})
);
}

function fail(error) {
Expand All @@ -26,10 +29,10 @@ function onRequest(req, res) {

function onBundle(error, bundle) {
if (error) {
return fail(error);
return void fail(error);
}
var htmlTpl = fs.readFileSync(BASE_HTML, 'utf8');
var html = htmlTpl + '<script>' + bundle + '</script>';
const htmlTpl = fs.readFileSync(BASE_HTML, 'utf8');
const html = `${htmlTpl}<script>${bundle}</script>`;
res.setHeader('Content-Type', 'text/html');
res.end(html);
}
Expand All @@ -43,6 +46,4 @@ function onListen() {
process.stdout.write('Listening on http://127.0.0.1:3000\n');
}

http
.createServer(onRequest)
.listen(3000, onListen);
http.createServer(onRequest).listen(3000, onListen);
189 changes: 85 additions & 104 deletions examples/github.js
Expand Up @@ -29,41 +29,67 @@ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

'use strict';
var assign = require('lodash/assign');
var omit = require('lodash/omit');

var Gofer = require('../');
var pkg = require('../package.json');
const Gofer = require('../');
const { version, name } = require('../package.json');

const DEFAULT_BASE_URL = 'https://api.github.com';

// Generate our ServiceClient class
function GithubClient() {
Gofer.call(this, 'github', pkg.version);
class GithubClient extends Gofer {
constructor(config) {
super(config, 'github', version, name);
}

createAccessToken(oauthCode) {
/**
* Exchange auth- for access token
*
* @see http://developer.github.com/v3/oauth/#web-application-flow
*/
return this.fetch('/login/oauth/access_token', {
endpointName: 'createAccessToken',
oauthCode,
method: 'POST',
json: true,
})
.json()
.then(res => res.access_token);
}

userRepos(username, qs) {
// fetch(url: string, options, callback)
return this.fetch(username ? '/users/{username}/repos' : '/user/repos', {
endpointName: 'userRepos',
pathParams: { username },
qs: Object.assign({ per_page: 100 }, qs),
}).json();
}

emojis() {
return this.fetch('/emojis', { endpointName: 'emojis' }).json();
}
}
GithubClient.prototype = Object.create(Gofer.prototype);
GithubClient.prototype.constructor = GithubClient;

var DEFAULT_BASE_URL = 'https://api.github.com';
GithubClient.prototype.addOptionMapper(function githubDefaults(opts) {
GithubClient.prototype.addOptionMapper(opts => {
// We extract all options we will be handling ourselves and then remove
// them, making sure nobody gets confused by them
var accessToken = opts.accessToken;
var oauthCode = opts.oauthCode;
var webUrl = opts.webUrl;
var clientId = opts.clientId;
var clientSecret = opts.clientSecret;

opts = omit(opts,
'accessToken',
'oauthCode',
'webUrl',
'clientId',
'clientSecret'
);
const {
accessToken,
oauthCode,
webUrl,
clientId,
clientSecret,
...otherOpts
} = opts;

opts = otherOpts;

if (accessToken) {
opts.headers = opts.headers || {};
opts.headers.authorization = 'token ' + accessToken;
opts.headers.authorization = `token ${accessToken}`;
}

// There's only call using this but since clientId, clientSecret and webUrl
Expand All @@ -77,70 +103,15 @@ GithubClient.prototype.addOptionMapper(function githubDefaults(opts) {
};
}

return assign({ baseUrl: DEFAULT_BASE_URL }, opts);
});

// Endpoints will be added to the prototype of the client, on access they
// will be initialized with a pre-configured function to make requests. The
// name of the function happens to be `request` because it (apart from some
// magical injection of parameters) forwards its arguments to request.
GithubClient.prototype.registerEndpoints({
// This is one possible style of "endpoint": a namespace for functions.
// Usage: `github.accessToken.create('my-code').pipe(process.stdout);`
accessToken: function accessToken(request) {
/**
* Exchange auth- for access token
*
* @see http://developer.github.com/v3/oauth/#web-application-flow
*/
return {
create: function create(oauthCode, cb) {
// request(uri: string, options, callback)
return request('/login/oauth/access_token', {
oauthCode: oauthCode,
json: true,
method: 'POST',
}, cb);
},
};
},

// Different style: "entity actions"
// Usage: `github.user('groupon').repos().pipe(process.stdout)`
user: function user(fetch) {
return function withUser(username) {
return {
repos: function repos(qs, cb) {
if (typeof qs === 'function') {
cb = qs;
qs = {};
}

// fetch(url: string, options, callback)
return fetch(username ? ('/users/{username}/repos') : '/user/repos', {
pathParams: { username: username },
qs: assign({ per_page: 100 }, qs),
}, cb);
},
};
};
},

// The simplest thing last: an endpoint that is just a method
// Usage: `github.emojis().pipe(process.stdout)`
emojis: function (fetch) {
return function emojis(cb) {
// fetch(url: string, options, callback)
return fetch('/emojis', {}, cb);
};
},
return Object.assign({ baseUrl: DEFAULT_BASE_URL }, opts);
});

module.exports = GithubClient;

if (require.main === module) {
/* eslint no-console:0 */
var github = new GithubClient({
/* eslint-disable no-console */

const github = new GithubClient({
globalDefaults: {
timeout: 5000,
connectTimeout: 1000,
Expand All @@ -152,35 +123,45 @@ if (require.main === module) {
});

// Get all supported emojis, dump response to stdout
github.emojis().json().then(console.log);
github
.emojis()
.json()
.then(console.log, console.error);

// List repos of the `groupon` github org
github.user('groupon').repos(function (err, repoList) {
if (err) throw err;
repoList.forEach(function (repo) {
github.userRepos('groupon').then(repoList => {
repoList.forEach(repo => {
console.log(repo.name, '\t#', repo.description);
});
});
}, console.error);

// Make a raw call to `/` (resource discovery)
github.fetch('/', function (err, data, response) {
if (err) throw err;
console.log('Status code: %d', response.statusCode);
console.log('Returned %d resources', Object.keys(data).length);
});
github
.fetch('/')
.then(response => {
console.log('Status code: %d', response.statusCode);
return response.json();
})
.then(data => {
console.log('Returned %d resources', Object.keys(data).length);
})
.catch(console.error);

// This is expected to fail unless you pass in a valid access token. If you
// do, this will output the first of your repos.
github.fetch('/user/repos', {
accessToken: process.env.GH_TOKEN,
}).done(function (myRepos) {
if (myRepos.length) {
console.log('One of your repos: %s', myRepos[0].name);
} else {
console.log('No repositories found');
github.userRepos({ accessToken: process.env.GH_TOKEN }).then(
myRepos => {
if (myRepos.length) {
console.log('One of your repos: %s', myRepos[0].name);
} else {
console.log('No repositories found');
}
},
error => {
console.log('Failed to get repos, try passing in an access token');
console.log(error.message);
}
}, function (error) {
console.log('Failed to get repos, try passing in an access token');
console.log(error.message);
});
);

/* eslint-enable no-console */
}

0 comments on commit 7296fe7

Please sign in to comment.