Skip to content

Commit

Permalink
Add custom user agent headers
Browse files Browse the repository at this point in the history
  • Loading branch information
jpadilla committed Nov 16, 2015
1 parent 1407e24 commit 84dd20a
Showing 1 changed file with 40 additions and 7 deletions.
47 changes: 40 additions & 7 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var request = require('request');
var exec = require('child_process').exec;

var API_URL = 'https://api.filepreviews.io/v2';
var FilePreviews;
Expand All @@ -20,6 +21,17 @@ FilePreviews = function(options) {
}
};

FilePreviews.VERSION = require('../package.json').version;
FilePreviews.CLIENT_UA_SERIALIZED = null;
FilePreviews.CLIENT_UA = {
lang: 'node',
publisher: 'filepreviews',
bindings_version: FilePreviews.VERSION,
lang_version: process.version,
platform: process.platform,
uname: null
};

FilePreviews.prototype.log = function(msg) {
if (this.debug) {
console.log(msg);
Expand Down Expand Up @@ -82,13 +94,30 @@ FilePreviews.prototype.request = function(url, options, callback) {
callback(body);
}.bind(this);

var getClientUserAgent = function(cb) {
if (FilePreviews.CLIENT_UA_SERIALIZED) {
return cb(FilePreviews.CLIENT_UA_SERIALIZED);
}

exec('uname -a', function(err, uname) {
FilePreviews.CLIENT_UA.uname = uname || 'UNKNOWN';
FilePreviews.CLIENT_UA_SERIALIZED = JSON.stringify(FilePreviews.CLIENT_UA);
cb(FilePreviews.CLIENT_UA_SERIALIZED);
});
};

var requestOptions = {
url: url,
method: _options.method || 'GET',
json: true,
auth: {
username: this.apiKey,
password: this.apiSecret
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'FilePreviews/v2 NodeBindings/' + FilePreviews.VERSION
}
};

Expand All @@ -98,13 +127,17 @@ FilePreviews.prototype.request = function(url, options, callback) {

this.log('API request to: ' + url);

this._request(requestOptions, function(error, response, body) {
if (error) {
onError(error, response, body);
} else {
onSuccess(error, response, body);
}
});
getClientUserAgent(function(clientUA) {
requestOptions.headers['X-FilePreviews-Client-User-Agent'] = clientUA;

this._request(requestOptions, function(error, response, body) {
if (error) {
onError(error, response, body);
} else {
onSuccess(error, response, body);
}
});
}.bind(this));
};

FilePreviews.prototype.getAPIRequestData = function(url, options) {
Expand Down

0 comments on commit 84dd20a

Please sign in to comment.