Skip to content

Instantly share code, notes, and snippets.

@lucnat
Created May 2, 2018 18:01
Show Gist options
  • Save lucnat/290dd4aa9c89e038d271841cbb2ceb8b to your computer and use it in GitHub Desktop.
Save lucnat/290dd4aa9c89e038d271841cbb2ceb8b to your computer and use it in GitHub Desktop.
Simple methods for bonobi api
// BaseURL = 'http://localhost:3030';
BaseURL = 'https://backend.bonobi.ch';
BaseAPI = BaseURL + '/api/v1';
// define authenticated and non-authenticated headers
Globals = {
authHeaders: {
'X-User-Id': localStorage.getItem('userId'),
'X-Auth-Token': localStorage.getItem('authToken'),
'Accept': 'application/json',
'Content-Type': 'application/json'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
// define authenticated api call
Globals.authCall = (method, URL, body, onsuccess, onerror) => {
fetch(URL, {
method: method,
headers: Globals.authHeaders,
body: body ? JSON.stringify(body) : null
})
.then((response) => response.json()).then((r) => {
if(r.status == 'error') {
if(onerror) onerror(r)
console.log(r.message);
}
else onsuccess(r);
}).catch((error) => { console.error(error); });
};
// api call without auth
Globals.call = (method, URL, body, onsuccess, onerror) => {
fetch(URL, {
method: method,
headers: Globals.headers,
body: body ? JSON.stringify(body) : null
})
.then((response) => response.json()).then((r) => {
if(r.status == 'error') {
if(onerror) onerror(r)
console.log(r.message);
}
else onsuccess(r);
}).catch((error) => { console.error(error); });
};
// usage GET request
Globals.authCall('GET',BaseAPI+'/entries',null,(r) => {
this.setState({ loading: false, entries: r.data})
});
// example login
handleLogin() {
this.setState({loading: true});
onsuccess = (r) => {
authInfo = r.data;
this.setState({'loading': false})
localStorage.setItem('userId', authInfo.userId);
localStorage.setItem('authToken', authInfo.authToken);
this.setState({'userId': authInfo.userId, 'authToken': authInfo.authToken});
localStorage.setItem('redirectedToLogin', 'no')
alert('Login successful', {timeout: 1000});
document.location.href = document.location.href;
};
onerror = (r) => {
this.setState({loading: false});
alert(r.message, {timeout: 1000});
};
var body = { email: this.state.email, password: this.state.password };
Globals.call('POST',BaseAPI+'/login',body,onsuccess, onerror);
}
// etc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment