UNPKG

ironwing

Version:

Ironwing is a lightweight front-end data library for model like data representations

119 lines (96 loc) 3.17 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _request = require('request'); var _request2 = _interopRequireDefault(_request); var _coreUtils = require('../../core/utils'); var RequestJSON = (function () { function RequestJSON() { _classCallCheck(this, RequestJSON); this.apiUrl = null; this.done = null; this.fail = null; } _createClass(RequestJSON, [{ key: 'setUrl', value: function setUrl(url) { this.apiUrl = (0, _coreUtils.checkURL)(url); } /** * Constructor * @param {String} url The API URL */ }, { key: 'init', value: function init(url) { this.apiUrl = (0, _coreUtils.checkURL)(url); this.done = null; this.fail = null; } }, { key: 'ajax', value: function ajax(method, url, async, data) { var _this = this; var options = getRequestOptions(method, this.apiUrl + url, data); (0, _request2['default'])(options, function (err, res, body) { if (err || !body) { _this.fail.call(); } else { _this.done.call(null, JSON.parse(body)); } }); } /** * URL getter * @return {String} URL string */ }, { key: 'getAPIURL', value: function getAPIURL() { return this.apiUrl; } /** * Callback which is if the request is done * @param {Function} callback Callback function * @return {Object} Mjs */ }, { key: 'onDone', value: function onDone(callback) { this.done = callback; return this; } /** * Callback which is if the request failed * @param {Function} callback Callback function * @return {Object} Mjs */ }, { key: 'onFail', value: function onFail(callback) { this.fail = callback; return this; } }]); return RequestJSON; })(); exports['default'] = RequestJSON; function getRequestOptions(method, url, data) { var options = { method: method.toUpperCase(), url: url, headers: { 'User-Agent': 'ironwing', 'Content-Type': 'application/json;charset=UTF-8' } }; if (options.method === 'POST' || options.method === 'PUT') { options.body = JSON.stringify(data); } return options; } module.exports = exports['default'];