ft_transcendence/frontend/static/js/api/client.js
2023-12-12 12:06:13 +01:00

127 lines
2.5 KiB
JavaScript

import { Account } from "./account.js";
import { MatchMaking } from "./matchmaking.js";
import { Profile } from "./profile.js";
import { Profiles } from "./profiles.js";
function getCookie(name)
{
let cookie = {};
document.cookie.split(';').forEach(function(el) {
let split = el.split('=');
cookie[split[0].trim()] = split.slice(1).join("=");
})
return cookie[name];
}
class Client
{
constructor(url)
{
this._url = url;
this.account = new Account(this);
this.profiles = new Profiles(this);
this.matchmaking = new MatchMaking(this);
this._logged = undefined;
}
async isAuthentificate()
{
if (this._logged == undefined)
this.logged = await this._test_logged();
return this.logged;
}
async _get(uri)
{
let response = await fetch(this._url + uri, {
method: "GET",
});
return response;
}
async _post(uri, data)
{
let response = await fetch(this._url + uri, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": getCookie("csrftoken"),
},
body: JSON.stringify(data),
});
return response;
}
async _delete(uri, data)
{
let response = await fetch(this._url + uri, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": getCookie("csrftoken"),
},
body: JSON.stringify(data),
});
return response;
}
async _patch_json(uri, data)
{
let response = await fetch(this._url + uri, {
method: "PATCH",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
return response;
}
async _patch_file(uri, file)
{
let response = await fetch(this._url + uri, {
method: "PATCH",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
},
body: file,
});
return response;
}
async login(username, password)
{
let response = await this._post("/api/accounts/login", {username: username, password: password})
let data = await response.json();
if (data.id != undefined)
{
this.me = new Profile(this)
await this.me.init(data.id)
this.logged = true;
return null;
}
return data;
}
async logout()
{
await this._get("/api/accounts/logout");
this.logged = false;
}
async _test_logged()
{
let response = await this._get("/api/accounts/logged");
let data = await response.json();
if (data.id !== undefined)
{
this.me = new Profile(this)
await this.me.init(data.id)
}
return data.id !== undefined;
}
}
export {Client}