js api refactoring

This commit is contained in:
Gwendolyn 2023-12-21 16:46:14 +01:00
parent 511a40fb5a
commit 9d8fbc808f
3 changed files with 20 additions and 33 deletions

View file

@ -1436,5 +1436,5 @@ LevelControl = L.Control.extend({
if ($('#sidebar').length) {
c3nav_api.authenticated().then(() => editor.init());
editor.init();
}

View file

@ -260,9 +260,6 @@ c3nav = {
//c3nav.test_location();
},
get_csrf_token: function() {
return document.cookie.match(new RegExp('c3nav_csrftoken=([^;]+)'))[1];
},
test_location: function() {
c3nav_api.get('positioning/locate-test')
.then(data => {
@ -1967,7 +1964,7 @@ c3nav = {
}
};
$(document).ready(() => {
c3nav_api.authenticated().then(c3nav.init);
c3nav.init();
});
function nearby_stations_available() {

View file

@ -9,7 +9,7 @@
}
authenticate() {
return fetch(this.base+'auth/session/', {
this.auth_promise = fetch(this.base+'auth/session/', {
credentials: 'same-origin',
method: 'GET',
})
@ -21,6 +21,7 @@
throw err;
})
.then(_ => null);
return this.auth_promise;
}
authenticated() {
@ -35,44 +36,33 @@
return url;
}
get(path) {
return fetch(this.make_url(path), {
async req(method, path, body) {
await this.auth_promise;
const init = {
credentials: 'include',
method: 'GET',
method: method,
headers: {
'X-API-Key': this.key,
'Accept': 'application/json'
}
})
.then(res => res.json())
};
if (typeof body !== 'undefined') {
init.body = JSON.stringify(body);
}
const res = await fetch(this.make_url(path), init);
return await res.json();
}
get(path) {
return this.req('GET', path);
}
post(path, data) {
return fetch(this.make_url(path), {
credentials: 'include',
method: 'POST',
headers: {
'X-API-Key': this.key,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(res => res.json())
return this.req('POST', path, data);
}
put(path, data) {
return fetch(this.make_url(path), {
credentials: 'include',
method: 'PUT',
headers: {
'X-API-Key': this.key,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(res => res.json())
return this.req('PUT', path, data);
}
}