Skip to content
This repository has been archived by the owner on Mar 25, 2018. It is now read-only.

Commit

Permalink
code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Sumit Goel committed Jan 25, 2018
1 parent 4fa7d2a commit 00f2652
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 176 deletions.
8 changes: 1 addition & 7 deletions examples/getAlarms.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,7 @@ const cg = new CloudGenix({
});

cg.login()
.then(() => cg.getAllEvents({
'exclude': [
'APPLICATION_APP_UNREACHABLE',
'APPLICATION_APP_UNKNOWN',
'APPLICATION_IP_COLLISION'
]
}))
.then(() => cg.getAllEvents())
.then((value) => {
console.log(JSON.stringify(value, null, 2), value.length);
return cg.logout();
Expand Down
178 changes: 73 additions & 105 deletions lib/api.js
Original file line number Diff line number Diff line change
@@ -1,150 +1,116 @@
/**
* Dependencies
*/
const debug = require('debug')('api');
const {vsprintf} = require('sprintf-js');
const req = require('./wrapper');
const conf = require('../config/defaults');

/**
* Cloud Genix API Client Object
*/
class CloudGenix {

/**
* Instantiate the API Client
*
* @param {Object} params API call parameters
*/
constructor (params) {
this.params = params;
this.url = params.url || conf.apiHost;
this.versionMap = Object.assign(conf.versionMap, params.versionMap);
this.uriMap = Object.assign(conf.uriMap, params.uriMap);
this.options = params.options || {};
this.token = null;
}

paramsValidation () {

// eslint-disable-next-line max-statements
return new Promise((resolve, reject) => {

const arr = [
'user',
'pass'
];

const hasUserPass = arr.every((item) => Object.prototype.hasOwnProperty
.call(this.params, item));

if (hasUserPass) {

if (!Object.prototype.hasOwnProperty.call(this.params, 'url')) {
this.params.url = 'https://api.cloudgenix.com';
}

if (!Object.prototype.hasOwnProperty.call(this.params, 'apiVersion')) {
this.params.apiVersion = 'v2.0';
}

if (!Object.prototype.hasOwnProperty.call(this.params, 'options')) {
this.params.options = {};
}

resolve(this.params);

} else {

reject(new Error('undefined: user and/or pass'));

}

}); // eslint: return promise
} // eslint: paramsValidation
if (params.user) {
this.user = params.user;
} else {
throw new Error('undefined user');
}

if (params.pass) {
this.pass = params.pass;
} else {
throw new Error('undefined password');
}
}

/**
* This method queries the permissions endpoint and add resource maps.
* This method allows to log in to the API and generate an authentication
* token for subsequent API calls.
*
* @returns {Promise} a promise which resolves to the http response.
*/
permissions () {
login () {
const version = this.versionMap.login;
const baseUrl = vsprintf(this.uriMap.login, [version]);

const opts = {
'uri': `${this.params.url}/${this.params.apiVersion}/api/permissions`,
return req.post({
'uri': `${this.url}${baseUrl}`,
'token': this.token,
'options': this.params.options
};

return req.get(opts).then((value) => {
this.versionMap = value.resource_version_map;
this.uriMap = value.resource_uri_map;
this.roleMap = value.resource_role_map;
return value;
});

} // eslint: permissions
'body': {
'email': this.user,
'password': this.pass
},
'options': this.options
})
.then((value) => {
debug('Login Response: %o', value);
this.token = value.x_auth_token;
return this.profile();
})
.then((value) => {
debug('Profile Response: %o', value);
return 'Success';
});
} // eslint: login

/**
* This method queries the profile endpoint and add tenant_id.
*
* @returns {Promise} a promise which resolves to the http response.
*/
profile () {

const version = this.versionMap.profile;
const baseUrl = this.uriMap.profile.replace('%s', version);
const baseUrl = vsprintf(this.uriMap.profile, [version]);

const opts = {
'uri': `${this.params.url}${baseUrl}`,
'uri': `${this.url}${baseUrl}`,
'token': this.token,
'options': this.params.options
'options': this.options
};

return req.get(opts).then((value) => {
this.tenantId = value.tenant_id;
return value;
});

} // eslint: profile

/**
* This method allows to log in to the API and generate an authentication
* token for subsequent API calls.
*
* @returns {Promise} a promise which resolves to the http response.
*/
login () {

const returnLoginPermResponse = {};

return this.paramsValidation().then(() => req.post({
'uri': `${this.params.url}/${this.params.apiVersion}/api/login`,
'token': this.token,
'body': {
'email': this.params.user,
'password': this.params.pass
},
'options': this.params.options
}))
.then((value) => {
this.token = value.x_auth_token;
returnLoginPermResponse.login = value;
return this.permissions();
})
.then((value) => {
returnLoginPermResponse.permissions = value;
return this.profile();
})
.then((value) => {
returnLoginPermResponse.profile = value;
return returnLoginPermResponse;
});

} // eslint: login

/**
* This method queries the events.
*
* @param {string} body - HTTP POST body
* @returns {Promise} a promise which resolves to the http response.
*/
queryEvents (body) {

const version = this.versionMap.query_events;
const baseUrl = `/${version}/api/tenants/${this.tenantId}/events/query`;
const baseUrl = vsprintf(this.uriMap.query_events, [
version,
this.tenantId
]);

const opts = {
'uri': `${this.params.url}${baseUrl}`,
'uri': `${this.url}${baseUrl}`,
'token': this.token,
'options': this.params.options,
'options': this.options,
body
};

return req.post(opts);

return req.post(opts).then((value) => {
debug('Query Events Response: %o', value);
return value;
});
} // eslint: queryEvents

/**
Expand All @@ -155,17 +121,19 @@ class CloudGenix {
*/
logout () {
const version = this.versionMap.logout;
const baseUrl = this.uriMap.logout.replace('%s', version);
const baseUrl = vsprintf(this.uriMap.logout, [version]);

const opts = {
'uri': `${this.params.url}${baseUrl}`,
'uri': `${this.url}${baseUrl}`,
'token': this.token,
'options': this.params.options
'options': this.options
};

return req.get(opts);
return req.get(opts).then((value) => {
debug('Logout Response: %o', value);
return value;
});
} // eslint: logout

} // eslint: class

module.exports = CloudGenix;
59 changes: 24 additions & 35 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,60 +1,49 @@
const debug = require('debug')('utils');
const CloudGenix = require('./api');
/**
* Dependencies
*/
const moment = require('moment');
const CloudGenix = require('./api');

/**
* Extending Cloud Genix API Client with helper methods
*/
class Client extends CloudGenix {

getAllEvents (options = {
'type': 'alarm',
'timeDelta': null,
'exclude': []
}) {

if (!Object.prototype.hasOwnProperty.call(options, 'type')) {
options.type = 'alarm';
}

if (!Object.prototype.hasOwnProperty.call(options, 'exclude')) {
options.exclude = [];
}
/**
* @param {Object} options - Options to get all events.
*
* @returns {Promise} a promise which resolves to all the events.
*/
getAllEvents (options = {}) {
let startTime = null;
let endTime = null;
let offset = null;
let items = [];

if (options.timeDelta) {
options.startTime = moment().subtract(options.timeDelta, 'm')
startTime = moment().subtract(options.timeDelta, 'm')
.toISOString();
options.endTime = moment().toISOString();
} else {
options.startTime = null;
options.endTime = null;
endTime = moment().toISOString();
}

let offset = null;
let items = [];

const events = () => this.queryEvents({
'_offset': offset,
'start_time': options.startTime,
'end_time': options.endTime,
'start_time': startTime,
'end_time': endTime,
'limit': {},
'query': {'type': options.type},
'severity': [],
'summary': false
'query': {},
'severity': []
}).then((value) => {

debug('Query Events: %o', value);

if (value._offset) { // eslint-disable-line no-underscore-dangle
offset = value._offset; // eslint-disable-line no-underscore-dangle
items = items.concat(value.items);
return events();
}

return items.concat(value.items);

}); // eslint: events

return events().then((value) => value.filter((item) => options.exclude
.includes(item.code) === false)); // eslint: return events

return events();
} // eslint: getAllEvents

} // eslint: Class Client
Expand Down
Loading

0 comments on commit 00f2652

Please sign in to comment.