Skip to content

Commit

Permalink
Add ability to set port/ssl
Browse files Browse the repository at this point in the history
  • Loading branch information
cbetta committed Feb 16, 2018
1 parent 6620b02 commit 175d9a0
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 42 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ module.exports = {
],
"no-console": [
"warn"
],
"no-trailing-spaces": [
"error"
]
}
};
9 changes: 5 additions & 4 deletions spec/amadeus/client/listener.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Listener from '../../../src/amadeus/client/listener';
import Response from '../../../src/amadeus/client/response';
import EventEmitter from 'events';
import Listener from '../../../src/amadeus/client/listener';
import Response from '../../../src/amadeus/client/response';
import { ResponseError } from '../../../src/amadeus/client/errors';
import EventEmitter from 'events';

let handler;
let request;
Expand Down Expand Up @@ -136,7 +137,7 @@ describe('Listener', () => {

handler.onNetworkError(response)();
expect(response.parse).toHaveBeenCalled();
expect(handler.emitter.emit).toHaveBeenCalledWith('reject', expect.any(Error));
expect(handler.emitter.emit).toHaveBeenCalledWith('reject', expect.any(ResponseError));
});
});
});
Expand Down
32 changes: 19 additions & 13 deletions spec/amadeus/client/request.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import Request from '../../../src/amadeus/client/request';

let host = 'test.api.amadeus.com';
let port = 443;
let verb = 'GET';
let ssl = true;
let path = '/foo/bar';
let params = { foo: 'bar' };
let bearerToken = 'token';
Expand All @@ -21,6 +23,8 @@ describe('Request', () => {
beforeEach(() => {
request = new Request({
host: host,
port: port,
ssl: ssl,
verb: verb,
path: path,
params: params,
Expand All @@ -44,7 +48,8 @@ describe('Request', () => {
expect(request.appVersion).toBe(appVersion);
expect(request.headers).toEqual({
'Accept': 'application/json',
'User-Agent': 'amadeus-node/1.2.3 node/2.3.4 amadeus-cli/3.4.5'
'User-Agent': 'amadeus-node/1.2.3 node/2.3.4 amadeus-cli/3.4.5',
'Authorization': 'Bearer token'
});
});

Expand Down Expand Up @@ -141,6 +146,7 @@ describe('Request', () => {
host: 'test.api.amadeus.com',
port: 443,
path: '/foo/bar?foo=bar',
protocol: 'https:',
headers: {
Accept: 'application/json',
Authorization: 'Bearer token',
Expand All @@ -153,32 +159,32 @@ describe('Request', () => {
describe('.addAuthorizationHeader', () => {
it('should add the authorization header if the token is present', () => {
request.bearerToken = '123456789';
let options = { headers: {} };
request.addAuthorizationHeader(options);
expect(options['headers']['Authorization']).toBe('Bearer 123456789');
request.headers = {};
request.addAuthorizationHeader();
expect(request.headers['Authorization']).toBe('Bearer 123456789');
});

it('skip if the token is not present', () => {
request.bearerToken = undefined;
let options = { headers: {} };
request.addAuthorizationHeader(options);
expect(options['headers']['Authorization']).toBeUndefined();
request.headers = {};
request.addAuthorizationHeader();
expect(request.headers['Authorization']).toBeUndefined();
});
});

describe('.addContentTypeHeader', () => {
it('should add the Content-Type header if the verb is POST', () => {
request.verb = 'POST';
let options = { headers: {} };
request.addContentTypeHeader(options);
expect(options['headers']['Content-Type']).toBe('application/x-www-form-urlencoded');
request.headers = {};
request.addContentTypeHeader();
expect(request.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
});

it('skip if the verb is not POST', () => {
request.verb = 'GET';
let options = { headers: {} };
request.addContentTypeHeader(options);
expect(options['headers']['Content-Type']).toBeUndefined();
request.headers = {};
request.addContentTypeHeader();
expect(request.headers['Content-Type']).toBeUndefined();
});
});
});
Expand Down
8 changes: 6 additions & 2 deletions src/amadeus.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,16 @@ import Travel from './amadeus/namespaces/travel';
* @param {Object} [params.logger=console] a `console`-compatible logger that
* accepts `log`, `error` and `debug` calls.
* @param {string} [params.hostname='production'] the name of the server API
* calls are made to (`production` or `test`)
* calls are made to (`production` or `test`)
* @param {string} [params.host] the full domain or IP for a server to make the
* API clal to. Only use this if you don't want to use the provided servers
* @param {boolean} [params.ssl=true] wether to use SSL for this API call
* @param {number} [params.port=443] the port to make the API call to
* @param {string} [params.customAppId=null] a custom App ID to be passed in
* the User Agent to the server.
* @param {string} [params.customAppVersion=null] a custom App Version number to
* be passed in the User Agent to the server.
* @param {Object} [params.http=https] an optional Node/HTTPS-compatible client
* @param {Object} [params.http=https] an optional Node/HTTP(S)-compatible client
* that accepts a 'request()' call with an array of options.
* @param {boolean} [params.debug=false] if this client is running in debug mode
*
Expand Down
11 changes: 8 additions & 3 deletions src/amadeus/client.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import EventEmitter from 'events';
import Promise from 'bluebird';
import util from 'util';

import AccessToken from './client/access_token';
import Listener from './client/listener';
Expand Down Expand Up @@ -29,11 +30,13 @@ import pkg from '../../package.json';
* the API
* @property {Object} logger the `console`-compatible logger used to debug calls
* @property {string} host the hostname of the server API calls are made to
* @property {number} port the port the server API calls are made to
* @property {boolean} ssl wether an SSL request is made to the server
* @property {string} customAppId the custom App ID to be passed in the User
* Agent to the server
* @property {string} customAppVersion the custom App Version number to be
* passed in the User Agent to the server
* @property {Object} http the Node/HTTPS-compatible client used to make
* @property {Object} http the Node/HTTP(S)-compatible client used to make
* requests
* @property {boolean} debug if this client is running in debug mode
* @property {number} version The version of this API client
Expand Down Expand Up @@ -158,7 +161,9 @@ class Client {
clientVersion: this.version,
languageVersion: process.version,
appId: this.customAppId,
appVersion: this.customAppVersion
appVersion: this.customAppVersion,
port: this.port,
ssl: this.ssl
});
}

Expand All @@ -185,7 +190,7 @@ class Client {
*/
log(request) {
/* istanbul ignore next */
if(this.debug) { this.logger.warn(request); }
if(this.debug) { this.logger.warn(util.inspect(request, false, null)); }
}
}

Expand Down
4 changes: 1 addition & 3 deletions src/amadeus/client/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@
* `AuthenticationError`, `NotFoundError` and `UnknownError`
* from the {@link Response}'s parsed data
*/
export class ResponseError extends Error {
export class ResponseError {
constructor(response) {
super();
Error.captureStackTrace(this, ResponseError);
this.response = response;
}
}
Expand Down
24 changes: 13 additions & 11 deletions src/amadeus/client/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import qs from 'qs';
*
* @property {string} host the host used for this API call
* @property {number} port the port for this API call. Standard set to 443.
* @property {boolean} ssl wether this API call uses SSL
* @property {string} scheme the scheme inferred from the SSL state
* @property {string} verb the HTTP method, for example `GET` or `POST`
* @property {string} path the full path of the API endpoint
* @property {Object} params the parameters to pass in the query or body
Expand All @@ -22,20 +24,24 @@ import qs from 'qs';
class Request {
constructor(options) {
this.host = options.host;
this.port = 443;
this.port = options.port;
this.ssl = options.ssl;
this.scheme = this.ssl ? 'https' : 'http';
this.verb = options.verb;
this.path = options.path;
this.params = options.params;
this.queryPath = this.fullQueryPath();
this.bearerToken = options.bearerToken;
this.clientVersion = options.clientVersion;
this.languageVersion = options.languageVersion;
this.languageVersion = options.languageVersion.replace('v', '');
this.appId = options.appId;
this.appVersion = options.appVersion;
this.headers = {
'User-Agent' : this.userAgent(),
'Accept' : 'application/json'
};
this.addAuthorizationHeader();
this.addContentTypeHeader();
}

// PROTECTED
Expand All @@ -53,13 +59,11 @@ class Request {
let options = {
'host' : this.host,
'port' : this.port,
'protocol' : `${this.scheme}:`,
'path' : this.queryPath,
'method' : this.verb,
'headers' : this.headers
};

this.addAuthorizationHeader(options);
this.addContentTypeHeader(options);
return options;
}

Expand Down Expand Up @@ -103,23 +107,21 @@ class Request {
/**
* Adds an Authorization header if the BearerToken is present
*
* @param {Object} options an associative array to add the header to
* @private
*/
addAuthorizationHeader(options) {
addAuthorizationHeader() {
if (!this.bearerToken) { return; }
options['headers']['Authorization'] = `Bearer ${this.bearerToken}`;
this.headers['Authorization'] = `Bearer ${this.bearerToken}`;
}

/**
* Adds an Content-Type header if the HTTP method equals POST
*
* @param {Object} options an associative array to add the header to
* @private
*/
addContentTypeHeader(options) {
addContentTypeHeader() {
if (this.verb !== 'POST') { return; }
options['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
this.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
}

Expand Down
21 changes: 15 additions & 6 deletions src/amadeus/client/validator.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import https from 'https';
import http from 'http';

const HOSTS = {
'test' : 'test.api.amadeus.com',
Expand All @@ -11,9 +12,12 @@ const RECOGNIZED_OPTIONS = [
'logger',
'debug',
'hostname',
'host',
'customAppId',
'customAppVersion',
'http'
'http',
'ssl',
'port'
];

/**
Expand Down Expand Up @@ -55,6 +59,8 @@ class Validator {
initializeHost(client, options) {
let hostname = this.initOptional('hostname', options, 'test');
client.host = this.initOptional('host', options, HOSTS[hostname]);
client.port = this.initOptional('port', options, 443);
client.ssl = this.initOptional('ssl', options, true);
}

initializeCustomApp(client, options) {
Expand All @@ -63,7 +69,8 @@ class Validator {
}

initializeHttp(client, options) {
client.http = this.initOptional('http', options, https);
let network = client.ssl ? https : http;
client.http = this.initOptional('http', options, network);
}

initRequired(key, options) {
Expand All @@ -73,10 +80,12 @@ class Validator {
}

initOptional(key, options, fallback = null) {
return options[key] ||
options[key.to_s] ||
process.env[`AMADEUS_${key.toUpperCase()}`] ||
fallback;
let value = options[key];
let envKey = `AMADEUS_${key.toUpperCase()}`;
if (value == undefined) { value = options[key]; }
if (value == undefined) { value = process.env[envKey]; }
if (value == undefined) { value = fallback; }
return value;
}

warnOnUnrecognizedOptions(options, logger, recognizedOptions) {
Expand Down

0 comments on commit 175d9a0

Please sign in to comment.