Created
March 28, 2017 09:30
-
-
Save anomaly44/9a00f202230dba740f7dcea01aea3bb3 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
import 'whatwg-fetch'; | |
import { validTokenPresent } from './checkAuth' | |
import { take, fork, cancel, call, put, cancelled, select } from 'redux-saga/effects' | |
function parseJSON(response) { | |
return response.json(); | |
} | |
function checkStatus(response) { | |
if (response.status >= 200 && response.status < 300) { | |
return response; | |
} | |
return parseJSON(response) | |
.then(parsedResponse => { | |
console.log(parsedResponse); | |
const error = new Error(parsedResponse.error); | |
error.statusText = response.statusText; | |
throw error; | |
}); | |
} | |
export default function request(url, options) { | |
return fetch(url, options) | |
.then(checkStatus) | |
.then(parseJSON); | |
} | |
export function* requestSaga(method, url, data) { | |
const headers = { | |
'Content-Type': 'application/json' | |
}; | |
const options = { | |
method: method, | |
headers: headers | |
}; | |
// retrieve token and set it if present | |
const token = validTokenPresent(); | |
if (token) headers['x-access-token'] = token; | |
if (data) options.body = JSON.stringify(data); | |
return yield call(request, url, options); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment