1
0
mirror of https://github.com/ascribe/onion.git synced 2024-11-15 09:35:10 +01:00
onion/js/utils/fetch.js

117 lines
2.8 KiB
JavaScript
Raw Normal View History

'use strict';
2015-06-01 14:22:04 +02:00
import { default as _fetch } from 'isomorphic-fetch';
2015-06-02 17:32:38 +02:00
import { argsToQueryParams } from '../utils/fetch_api_utils';
2015-06-01 14:22:04 +02:00
class UrlMapError extends Error {}
class ServerError extends Error {}
class APIError extends Error {}
2015-06-01 14:22:04 +02:00
class Fetch {
_merge(defaults, options) {
let merged = {};
for (let key in defaults) {
merged[key] = defaults[key];
}
for (let key in options) {
merged[key] = options[key];
}
return merged;
}
unpackResponse(response) {
if (response.status >= 500) {
throw new ServerError();
}
return response.text();
}
handleFatalError(err) {
this.fatalErrorHandler(err);
throw new ServerError(err);
}
handleAPIError(json) {
if (!json.success) {
2015-06-01 14:22:04 +02:00
let error = new APIError();
error.json = json;
throw error;
}
return json;
}
getUrl(url) {
let name = url;
if (!url.match(/^http/)) {
url = this.urlMap[url];
if (!url) {
throw new UrlMapError(`Cannot find a mapping for "${name}"`);
}
}
return url;
}
2015-06-01 16:45:09 +02:00
prepareUrl(url, params, attachParamsToQuery) {
2015-06-01 14:22:04 +02:00
let newUrl = this.getUrl(url);
let re = /\${(\w+)}/g;
2015-06-02 16:47:25 +02:00
2015-06-01 14:22:04 +02:00
newUrl = newUrl.replace(re, (match, key) => {
let val = params[key];
2015-06-01 14:22:04 +02:00
if (!val) {
throw new Error(`Cannot find param ${key}`);
}
delete params[key];
return val;
});
2015-06-01 16:45:09 +02:00
if (attachParamsToQuery && params && Object.keys(params).length > 0) {
newUrl += argsToQueryParams(params);
2015-06-01 14:22:04 +02:00
}
return newUrl;
}
request(verb, url, options) {
options = options || {};
let merged = this._merge(this.httpOptions, options);
merged.method = verb;
2015-06-01 16:45:09 +02:00
return _fetch(url, merged)
.then(this.unpackResponse)
.then(JSON.parse)
.catch(this.handleFatalError.bind(this))
.then(this.handleAPIError);
2015-06-01 14:22:04 +02:00
}
2015-06-01 16:45:09 +02:00
get(url, params) {
let paramsCopy = this._merge(params);
2015-06-02 14:33:00 +02:00
let newUrl = this.prepareUrl(url, params, true);
return this.request('get', newUrl);
2015-06-01 14:22:04 +02:00
}
2015-06-01 16:45:09 +02:00
post(url, params) {
let paramsCopy = this._merge(params);
let newUrl = this.prepareUrl(url, params);
2015-06-01 17:43:38 +02:00
let body = null;
if (params.body) {
body = JSON.stringify(params.body);
2015-06-01 17:43:38 +02:00
}
2015-06-01 16:45:09 +02:00
return this.request('post', url, { body });
2015-06-01 14:22:04 +02:00
}
defaults(options) {
this.httpOptions = options.http || {};
this.urlMap = options.urlMap || {};
this.fatalErrorHandler = options.fatalErrorHandler || (() => {});
}
}
let fetch = new Fetch();
export default fetch;