-
-
Save xbenjii/85f89b1b7bfdbaf09467 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
import * as qs from 'querystring'; | |
import * from 'xml2js'; | |
import * as Promise from 'bluebird'; | |
import * as request from 'request-promise'; | |
let parseString = Promise.promisify(xml2js.parseString); | |
class Preston { | |
constructor(shopUrl, key, options = {}) { | |
if (!shopUrl) { | |
throw new Error('Shop URL required'); | |
} | |
if (!key) { | |
throw new Error('API key required'); | |
} | |
this.shopUrl = shopUrl; | |
this.key = key; | |
this.options = options; | |
} | |
executeRequest(method, url, options = {}) { | |
return request[method](url, options).auth(this.key); | |
} | |
parse(response) { | |
return parseString(response); | |
} | |
get(resource, options = {}) { | |
let url, requestOptions = {}; | |
if(/^https?/.test(resource)) { | |
url = resource; | |
} else { | |
url = `${this.shopUrl}/api/${resource}/`; | |
} | |
if(options.id) { | |
url += options.id; | |
delete options.id; | |
} | |
['filter', 'display', 'sort', 'limit', 'id_shop', 'id_group_shop'].forEach(param => { | |
if(options[param]) { | |
requestOptions[param] = options[param]; | |
} | |
}); | |
url += qs.stringify(requestOptions); | |
return this.executeRequest('get', url).then(response => this.parse(response)); | |
} | |
} | |
export default Preston; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment