1
0
mirror of https://github.com/ascribe/onion.git synced 2024-12-23 09:50:31 +01:00
onion/js/utils/fetch_api_utils.js

70 lines
1.8 KiB
JavaScript
Raw Normal View History

'use strict';
2015-07-24 13:44:28 +02:00
import Q from 'q';
import moment from 'moment';
2015-07-24 13:44:28 +02:00
2015-07-16 18:27:34 +02:00
import AppConstants from '../constants/application_constants';
2015-05-19 17:01:28 +02:00
// TODO: Create Unittests that test all functions
export function status(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
throw new Error(response.json());
}
2015-06-16 14:01:53 +02:00
export function getCookie(name) {
2015-07-16 17:04:37 +02:00
let parts = document.cookie.split(';');
2015-07-16 17:04:37 +02:00
for(let i = 0; i < parts.length; i++) {
if(parts[i].indexOf(name + '=') > -1) {
2015-07-16 17:04:37 +02:00
return parts[i].split('=').pop();
}
2015-06-16 14:01:53 +02:00
}
}
export function setCookie(key, value, days) {
const exdate = moment();
exdate.add(days, 'days');
value = window.escape(value) + ((days === null) ? '' : `; expires= ${exdate.utc()}`);
document.cookie = `${key}=${value}`;
}
/*
Given a url for an image, this method fetches it and returns a promise that resolves to
a blob object.
It can be used to create a 64base encoded data url.
Taken from: http://jsfiddle.net/jan_miksovsky/yy7zs/
CURRENTLY NOT USED...
*/
export function fetchImageAsBlob(url) {
2015-07-24 13:44:28 +02:00
return Q.Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// Ask for the result as an ArrayBuffer.
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status >= 400) {
reject(xhr.statusText);
}
};
xhr.onload = function() {
// Obtain a blob: URL for the image data.
let arrayBufferView = new Uint8Array(this.response);
let blob = new Blob([arrayBufferView], {type: 'image/jpeg'});
resolve(blob);
};
xhr.send();
});
}