42_ft_transcendence/frontend/static/js/api/profile.js
2024-03-31 10:59:39 +02:00

101 lines
2.0 KiB
JavaScript

import { Client } from "./client.js";
class Profile
{
/**
* @param {Client} client
*/
constructor (client, username=undefined, id=undefined, avatar_url=undefined)
{
/**
* @type {Client} client
*/
this.client = client;
/**
* @type {String}
*/
this.username = username;
/**
* @type {Number}
*/
this.id = id;
/**
* @type {String}
*/
this.avatar_url = avatar_url;
/**
* @type {Boolean}
*/
this.isBlocked = false;
this.isFriend = false;
}
/**
*
* @returns {Promise<*>}
*/
async init()
{
let response;
if (this.username !== undefined)
response = await this.client._get(`/api/profiles/user/${this.username}`);
else
response = await this.client._get(`/api/profiles/id/${this.id}`);
if (response.status !== 200)
return response.status;
let response_data = await response.json();
this.id = response_data.user_id;
this.username = response_data.username;
this.avatar_url = response_data.avatar;
await this.getBlock();
await this.getFriend();
}
async getBlock() {
let block_response = await this.client._get("/api/profiles/block");
if (block_response.status != 200)
return;
let block_data = await block_response.json();
let block_list = JSON.parse(block_data.blockeds);
let client_id = block_data.user_id;
block_list.forEach(block => {
let blocker = block.fields.blocker;
let blocked = block.fields.blocked;
if (blocker == client_id && blocked == this.id)
return (this.isBlocked = true);
});
}
async getFriend() {
let friend_response = await this.client._get("/api/profiles/friend");
this.isFriend = false;
if (friend_response.status != 200)
return this.isFriend;
let friend_data = await friend_response.json();
let friends_list = friend_data.friends;
let client_id = friend_data.user_id;
friends_list.forEach(friend => {
if (friend == this.id) {
this.isFriend = true;
return this.isFriend;
}
});
return this.isFriend;
}
}
export {Profile};