ft_transcendence/frontend/static/js/api/client.js
2023-11-27 19:16:30 +01:00

48 lines
952 B
JavaScript

import { Accounts } from "./accounts.js";
function extract_token(response)
{
let cookies = response.headers.get("set-cookie");
if (cookies == null)
return null;
let token = cookies.slice(cookies.indexOf("=") + 1, cookies.indexOf(';'))
return token;
}
class Client
{
constructor(url)
{
this._url = url;
this.accounts = new Accounts(this);
this._token = undefined;
}
isAuthentificate()
{
return this.token != undefined;
}
async _post(uri, data)
{
let response = await fetch(this._url + uri, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
let token = extract_token(response);
if (token != null)
this.token = token;
return response;
}
async login(username, password)
{
let response = await this._post("/api/accounts/login", {username: username, password: password})
return response
}
}
export {Client}