Skip to content

Commit

Permalink
feat(rest): add support for transforming JSON and XML responses
Browse files Browse the repository at this point in the history
  • Loading branch information
Benjamin Reed committed Jun 6, 2017
1 parent bed6390 commit 27e5578
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/rest/AbstractHTTP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import {OnmsHTTPOptions} from '../api/OnmsHTTPOptions';
import {OnmsResult} from '../api/OnmsResult';
import {OnmsServer} from '../api/OnmsServer';

// tslint:disable-next-line
const X2JS = require('x2js');
const xmlParser = new X2JS();

/**
* Implementation of the OnmsHTTP interface using Axios: https://github.com/mzabriskie/axios
* @module AxiosHTTP
Expand Down Expand Up @@ -45,6 +49,39 @@ export abstract class AbstractHTTP implements IOnmsHTTP {
/** make an HTTP get call -- this should be overridden by the implementation */
public abstract get(url: string, options?: OnmsHTTPOptions): Promise<OnmsResult<any>>;

/** a convenience method for implementers to use to turn JSON into a javascript object */
protected transformJSON(data: any) {
if (typeof data === 'string') {
return JSON.parse(data);
} else {
// assume it's already parsed
return data;
}
}

/** a convenience method for implementers to use to turn XML into a javascript object */
protected transformXML(data: any) {
if (typeof data === 'string') {
return xmlParser.xml2js(data);
} else {
// assume it's already parsed
return data;
}
}

/** combine all options from the given options, the current server, and the default options */
protected getOptions(options?: OnmsHTTPOptions) {
let ret = Object.assign({auth: {}}, this.options);
if (this.timeout) {
ret.timeout = this.timeout;
}
if (this.serverObj && this.serverObj.auth) {
ret.auth = Object.assign(ret.auth, this.serverObj.auth);
}
ret = Object.assign(ret, options);
return ret;
}

/** useful for performing an action (like clearing caches) when the server is set */
protected onSetServer() {
// do nothing by default
Expand Down

0 comments on commit 27e5578

Please sign in to comment.