Compare commits

...

10 commits

Author SHA1 Message Date
Todd Treece
78b44403d4 2.0.1 2016-05-27 14:04:16 -04:00
Todd Treece
6489dbe917 fix readme example path issue 2016-05-27 14:03:50 -04:00
Todd Treece
160b526d85 2.0.0 2016-05-27 13:45:43 -04:00
Todd Treece
1ea770eda1 update node version in travis config 2016-05-27 13:42:23 -04:00
Todd Treece
f0707dde6b update readme examples 2016-05-27 13:38:21 -04:00
Todd Treece
913d96e88c es6 update for examples 2016-05-27 13:34:07 -04:00
Todd Treece
e5fce06c9a tests need to use the 'new' keyword 2016-05-27 13:16:38 -04:00
Todd Treece
730252e529 es6 updates for helpers 2016-05-27 13:16:02 -04:00
Todd Treece
2a3d76914e es6 changes for npr one module 2016-05-27 13:15:09 -04:00
Todd Treece
e6114d3907 update main module to es6 class 2016-05-27 13:14:53 -04:00
10 changed files with 191 additions and 260 deletions

View file

@ -1,6 +1,6 @@
language: node_js
node_js:
- '0.12'
- "6"
before_script:
- npm install -g gulp
notifications:

View file

@ -9,7 +9,7 @@ the latest stable version of [node.js](https://nodejs.org).
```
$ node -v
v0.12.7
v6.2.0
```
## Installation
@ -25,25 +25,23 @@ As of right now, the full [NPR One API](http://dev.npr.org/api/) is available in
It is also set up in a way where it will support the future addition of other [NPR 'Open APIs'](http://www.npr.org/templates/apidoc/)
by adding additional API modules to the `lib/` folder.
**Note:** The only known limitation is that NPR One API module included in this package currently expects
to use the `grant_type` of *password* to get new OAuth access tokens. The other authentication methods will be supported soon.
### Example
First, you will need to create a new file called `get_token.js` in your favorite text editor.
```
```sh
$ vim get_token.js
```
Then, paste the example below into the file and update the creditials to match your NPR Developer account info.
```
var NPR = require('../index'),
npr = NPR();
```js
const NPR = require('npr-api'),
npr = new NPR();
var client_id = 'your_oauth_client_id',
client_secret = 'your_oauth_client_secret';
const client_id = 'your_oauth_client_id',
client_secret = 'your_oauth_client_secret';
npr.one.init()
.then(function() {
@ -61,8 +59,8 @@ npr.one.init()
return new Promise(function(resolve, reject) {
console.log('Please visit the following URL:');
console.log(res.verification_uri + '\n');
console.log('Enter code: ' + res.user_code + '\n');
console.log(`${res.verification_uri}\n`);
console.log(`Enter code: ${res.user_code}\n`);
console.log('Press the Spacebar when complete.');
process.stdin.setRawMode(true);
@ -85,7 +83,7 @@ npr.one.init()
});
})
.then(function(res) {
console.log('ACCESS TOKEN: ' + res.access_token);
console.log(`ACCESS TOKEN: ${res.access_token}`);
process.exit();
})
.catch(function(err) {
@ -96,25 +94,25 @@ npr.one.init()
Then, run the example using `node`.
```
```sh
$ node get_token.js
```
You will only need this once to get an access token to use from
now on. Next, you will need to create a new file called `index.js` in your favorite text editor.
now on. Next, you will need to create a new file called `get_recommendations.js` in your favorite text editor.
```
$ vim index.js
```sh
$ vim get_recommendations.js
```
Then, paste the example below into the file and update the creditials to match your NPR Developer account info.
```
var NPR = require('npr-api'),
npr = NPR();
```js
const NPR = require('npr-api'),
npr = new NPR();
// paste in your token here
var token = 'access_token_from_step_1';
const token = 'access_token_from_step_1';
npr.one.init(token)
.then(function() {
@ -129,7 +127,7 @@ npr.one.init(token)
Then, run the example using `node`.
```
$ node index.js
$ node get_recommendations.js
```
You should then see a couple of the listening recommendations for your NPR account dumped to your terminal's `stdout`.

View file

@ -1,8 +1,8 @@
var NPR = require('../index'),
npr = NPR();
const NPR = require('../index'),
npr = new NPR();
// paste in your token here
var token = process.env.ACCESS_TOKEN || 'access_token_from_step_1';
// paste in your token here or use env var
const token = process.env.ACCESS_TOKEN || 'access_token_from_step_1';
npr.one.init(token)
.then(function() {

View file

@ -1,8 +1,8 @@
var NPR = require('../index'),
npr = NPR();
const NPR = require('../index'),
npr = new NPR();
var client_id = process.env.CLIENT_ID || 'your_oauth_client_id',
client_secret = process.env.CLIENT_SECRET || 'your_oauth_client_secret';
const client_id = process.env.CLIENT_ID || 'your_oauth_client_id',
client_secret = process.env.CLIENT_SECRET || 'your_oauth_client_secret';
npr.one.init()
.then(function() {
@ -20,8 +20,8 @@ npr.one.init()
return new Promise(function(resolve, reject) {
console.log('Please visit the following URL:');
console.log(res.verification_uri + '\n');
console.log('Enter code: ' + res.user_code + '\n');
console.log(`${res.verification_uri}\n`);
console.log(`Enter code: ${res.user_code}\n`);
console.log('Press the Spacebar when complete.');
process.stdin.setRawMode(true);
@ -44,7 +44,7 @@ npr.one.init()
});
})
.then(function(res) {
console.log('ACCESS TOKEN: ' + res.access_token);
console.log(`ACCESS TOKEN: ${res.access_token}`);
process.exit();
})
.catch(function(err) {

View file

@ -1,36 +1,8 @@
require('dotenv').load();
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
mocha = require('gulp-mocha');
gulp.task('lint', function() {
var lint = jshint({
"curly": false,
"eqeqeq": true,
"immed": true,
"latedef": "nofunc",
"newcap": false,
"noarg": true,
"sub": true,
"undef": false,
"unused": "var",
"boss": true,
"eqnull": true,
"node": true,
"-W086": true
});
return gulp.src([
'index.js',
'lib/*.js',
'test/*.js'
]).pipe(lint)
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('test', function() {
return gulp.src('test/*.js', {read: false})
@ -45,4 +17,4 @@ gulp.task('test', function() {
});
gulp.task('default', ['lint', 'test']);
gulp.task('default', ['test']);

View file

@ -1,34 +1,32 @@
/************************ DEPENDENCIES *****************************/
var shim = require('es6-shim'),
util = require('util'),
bunyan = require('bunyan'),
One = require('./lib/one'),
Helpers = require('./lib/helpers');
'use strict';
var proto = NPR.prototype;
exports = module.exports = NPR;
const bunyan = require('bunyan'),
One = require('./lib/one'),
Helpers = require('./lib/helpers');
/************************* CONSTRUCTOR ****************************/
function NPR(config) {
class NPR {
if (! (this instanceof NPR))
return new NPR(config);
constructor(config) {
util._extend(this, config || {});
Object.assign(this, config || {});
if (! this.log)
this.log = bunyan.createLogger({name: 'npr'});
if (! this.log)
this.log = bunyan.createLogger({name: 'npr'});
this.one = One({
log: this.log.child({ module: 'one' })
});
this.one = new One({
log: this.log.child({ module: 'one' })
});
}
static Helpers() {
return Helpers;
}
static One() {
return One;
}
}
/**************************** STATIC ******************************/
NPR.Helpers = Helpers;
NPR.One = One;
/*************************** DEFAULTS *****************************/
proto.one = false;
proto.log = false;
exports = module.exports = NPR;

View file

@ -1,62 +1,18 @@
var util = require('util');
'use strict';
/************************ PROMISIFY *****************************/
function success(resolve, response) {
const success = (resolve, response) => {
resolve(response.obj);
}
function fail(reject, response) {
reject(response);
}
exports.promisify = function(module, operation, parameters) {
return function() {
var self = this,
args = Array.prototype.slice.call(arguments);
var require_auth = parameters.find(function(param) {
return param.name === 'Authorization';
});
var promise = function(access_token) {
return new Promise(function(resolve, reject) {
if(access_token) {
if(! args[0])
args[0] = {};
args[0].Authorization = 'Bearer ' + access_token;
}
args.push(success.bind(null, resolve));
args.push(fail.bind(null, reject));
operation.apply(self, args);
});
};
if(require_auth)
return module.getAccessToken().then(promise);
return promise();
};
};
/********************* SWAGGER FIXES ****************************/
function processAPI(module, api) {
const fail = (reject, response) => {
reject(response);
};
var processed = {};
const processAPI = (module, api) => {
Object.keys(api.operations).forEach(function(operation) {
const processed = {};
Object.keys(api.operations).forEach((operation) => {
processed[operation] = exports.promisify(
module,
api[operation],
@ -66,13 +22,52 @@ function processAPI(module, api) {
return processed;
}
};
exports.processSwagger = function(module) {
const applyAuth = (operation, args, access_token) => {
var apis = {};
return new Promise((resolve, reject) => {
Object.keys(module.client.apis).forEach(function(api) {
if(access_token) {
if(! args[0])
args[0] = {};
args[0].Authorization = 'Bearer ' + access_token;
}
args.push(success.bind(null, resolve));
args.push(fail.bind(null, reject));
operation.apply(this, args);
});
};
exports.promisify = (module, operation, parameters) => {
return (...args) => {
const require_auth = parameters.find((param) => {
return param.name === 'Authorization';
});
if(require_auth)
return module.getAccessToken().then(applyAuth.bind(this, operation, args));
return applyAuth.call(this, operation, args);
};
};
exports.processSwagger = (module) => {
const apis = {};
Object.keys(module.client.apis).forEach((api) => {
if(api === 'help')
return;
@ -81,8 +76,6 @@ exports.processSwagger = function(module) {
});
util._extend(module, apis || {});
Object.assign(module, apis || {});
};
module.exports = exports;

View file

@ -1,90 +1,82 @@
/************************ DEPENDENCIES *****************************/
var util = require('util'),
bunyan = require('bunyan'),
helpers = require('./helpers'),
swagger = require('swagger-client');
'use strict';
var proto = One.prototype;
exports = module.exports = One;
const bunyan = require('bunyan'),
helpers = require('./helpers'),
Swagger = require('swagger-client');
/************************* CONSTRUCTOR ****************************/
function One(config) {
class One {
if (! (this instanceof One))
return new One(config);
constructor(config) {
util._extend(this, config || {});
this.token = false;
this.swagger_url = 'https://api.npr.org/documentation/beryllium/api-docs';
this.log = false;
if(! this.log)
this.log = bunyan.createLogger({name: 'npr-one'});
Object.assign(this, config || {});
// silence swagger log output
process.env.NODE_ENV = 'test';
if(! this.log)
this.log = bunyan.createLogger({name: 'npr-one'});
// silence swagger log output
process.env.NODE_ENV = 'test';
}
init(token) {
if(token)
this.setAccessToken(token);
return new Promise((resolve, reject) => {
const client = new Swagger({
url: this.swagger_url,
success: () => {
this.client = client;
helpers.processSwagger(this);
resolve(this);
},
failure: () => {
reject('swagger init failed');
}
});
});
}
setAccessToken(token) {
this.token = token;
return new Promise((resolve, reject) => {
if(! this.token)
return reject('no token supplied');
const auth = new Swagger.ApiKeyAuthorization('Authorization', `Bearer ${token}`, 'header');
this.client.clientAuthorizations.add('oauth2', auth);
resolve();
});
}
getAccessToken() {
return new Promise((resolve, reject) => {
if(! this.token)
return reject('no token supplied');
resolve(this.token);
});
}
}
/*************************** DEFAULTS *****************************/
proto.token = false;
proto.swagger_url = 'https://api.npr.org/documentation/beryllium/api-docs';
proto.log = false;
proto.init = function(token) {
var self = this;
if(token)
this.setAccessToken(token);
return new Promise(function(resolve, reject) {
var client = new swagger({
url: self.swagger_url,
success: function() {
self.client = client;
helpers.processSwagger(self);
resolve(self);
},
failure: function() {
reject('swagger init failed');
}
});
});
};
proto.setAccessToken = function(token) {
var self = this;
this.token = token;
return new Promise(function(resolve, reject) {
if(! self.token)
return reject('no token supplied');
var auth = new swagger.ApiKeyAuthorization('Authorization', 'Bearer ' + token, 'header');
self.client.clientAuthorizations.add('oauth2', auth);
resolve();
});
};
proto.getAccessToken = function() {
var self = this;
return new Promise(function(resolve, reject) {
if(! self.token)
return reject('no token supplied');
resolve(self.token);
});
};
exports = module.exports = One;

View file

@ -1,6 +1,6 @@
{
"name": "npr-api",
"version": "1.1.2",
"version": "2.0.1",
"description": "Node.js NPR API client",
"main": "index.js",
"scripts": {
@ -32,7 +32,6 @@
},
"dependencies": {
"bunyan": "^1.4.0",
"es6-shim": "^0.32.2",
"swagger-client": "^2.1.2"
}
}

View file

@ -5,13 +5,13 @@ process.env.NODE_ENV = 'test';
describe('NPR One', function() {
this.timeout(10000);
describe('Init', function() {
this.timeout(15000);
it('should create a client', function(done) {
npr = NPR();
npr = new NPR();
npr.one.init()
.then(function() { done(); })
@ -23,38 +23,19 @@ describe('NPR One', function() {
describe('Authorization', function() {
it('should get an access token using password grant type', function(done) {
npr.one.authorization
.createToken({
grant_type: 'password',
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
username: process.env.NPR_USERNAME,
password: process.env.NPR_PASSWORD
})
.then(function(res) {
if(! res.access_token)
return done('missing access token');
npr.one.setAccessToken(res.access_token);
done();
}).catch(done);
it('should set access token without error', function(done) {
npr.one.setAccessToken(process.env.NPR_ACCESS_TOKEN).then(function() { return done(); }).catch(done);
});
});
describe('Listening', function() {
this.timeout(15000);
it('should get channels', function(done) {
npr.one.listening
.getChannels()
.then(function(res) {
npr.one.listening.getChannels().then(function(res) {
if(! res.items.length)
return done('missing channels');
@ -67,9 +48,7 @@ describe('NPR One', function() {
it('should get history', function(done) {
npr.one.listening
.getHistory()
.then(function(res) {
npr.one.listening.getHistory().then(function(res) {
if(! res.items.length)
return done('missing history');