2023-11-27 09:32:17 -05:00
|
|
|
import { Accounts } from "./accounts.js";
|
|
|
|
|
|
|
|
function extract_token(response)
|
|
|
|
{
|
|
|
|
let cookies = response.headers.get("set-cookie");
|
|
|
|
if (cookies == null)
|
|
|
|
return null;
|
2023-11-27 13:16:30 -05:00
|
|
|
let token = cookies.slice(cookies.indexOf("=") + 1, cookies.indexOf(';'))
|
2023-11-27 09:32:17 -05:00
|
|
|
return token;
|
|
|
|
}
|
|
|
|
|
2023-11-23 11:26:09 -05:00
|
|
|
class Client
|
|
|
|
{
|
|
|
|
constructor(url)
|
|
|
|
{
|
|
|
|
this._url = url;
|
2023-11-27 09:32:17 -05:00
|
|
|
this.accounts = new Accounts(this);
|
2023-11-23 11:26:09 -05:00
|
|
|
this._token = undefined;
|
|
|
|
}
|
|
|
|
|
2023-11-27 13:16:30 -05:00
|
|
|
isAuthentificate()
|
2023-11-23 11:26:09 -05:00
|
|
|
{
|
|
|
|
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),
|
|
|
|
});
|
2023-11-27 09:32:17 -05:00
|
|
|
let token = extract_token(response);
|
|
|
|
if (token != null)
|
|
|
|
this.token = token;
|
2023-11-23 11:26:09 -05:00
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
async login(username, password)
|
|
|
|
{
|
2023-11-27 09:32:17 -05:00
|
|
|
let response = await this._post("/api/accounts/login", {username: username, password: password})
|
|
|
|
return response
|
2023-11-23 11:26:09 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export {Client}
|