add: documentation and init post

This commit is contained in:
starnakin 2023-11-08 13:16:58 +01:00
parent a9cd640a75
commit fc9dcfbdf9

View File

@ -1,23 +1,101 @@
/**
* return the token from response
*
* @param {Response} response - The reponse
*/
function extract_csrf_token(response)
{
let cookies = response.headers.get("set-cookie");
csrf_token = cookies.slice(cookies.indexOf("=") + 1, cookies.indexOf(';'))
return csrf_token;
}
class Client class Client
{ {
/**
* Create a client to interract with the api
*
* @param {string} url - The url of the backend
*/
constructor(url) constructor(url)
{ {
/**
* The api token to be logged
* @type string */
this.token = undefined; this.token = undefined;
/**
* The django csrftoken to send post data
* @type string */
this.csrf_token = undefined; this.csrf_token = undefined;
/**
* The django csrfmiddlewaretoken to send post data
* @type string */
this.csrfmiddlewaretoken = undefined
/**
* The api url
* @type string */
this.url = url; this.url = url;
} }
/**
* return if the client is logged
*/
get isAuthentificate() get isAuthentificate()
{ {
return this.token != undefined; return this.token != undefined;
} }
/**
* A no consummer function to send get requests
*
* @param {string} uri - The path want to get
*/
async _get(uri) async _get(uri)
{ {
let url = this.url + uri let url = this.url + uri
console.log(url) let response = await fetch(url);
let response; this.csrf_token = extract_csrf_token(response);
response = await fetch(url); return response;
}
/**
* A no consummer function to send post requests
*
* @param {string} uri - The path want to post
*/
async _post(uri, data)
{
let url = this.url + uri
if (this.csrf_token === undefined)
{
let response = await fetch(url);
this.csrf_token = extract_csrf_token(response);
}
let response = await fetch(url, {
method: "POST",
headers: {
'Referer': url,
},
body: objectToFormData(data),
});
console.log(response.status)
return response;
}
/**
* Login your client with username and password
*
* @param {string} username - The username of the client
* @param {string} password - The password of the client
*/
async login(username, password)
{
let response = this._post(accounts_login, {'username': username, 'password': password})
return response; return response;
} }
} }
@ -28,6 +106,7 @@ let url = "http://0.0.0.0:8000/"
let client = new Client(url) let client = new Client(url)
console.log((await client._get(accounts_login))) await client._get(accounts_login)
await client.login("bozoman", "man")
export {client} export {Client}