Files
milsim-site-v4/ui/src/api/roles.ts
2025-12-18 15:12:22 -05:00

120 lines
3.0 KiB
TypeScript

import { Member, MemberLight } from "@shared/types/member";
import { Role } from "@shared/types/roles";
// @ts-ignore
const addr = import.meta.env.VITE_APIHOST;
export async function getRoles(): Promise<Role[]> {
const res = await fetch(`${addr}/roles`, {
credentials: 'include',
})
if (res.ok) {
return res.json() as Promise<Role[]>;
} else {
console.error("Something went wrong")
return [];
}
}
export async function getRoleDetails(id: number): Promise<Role> {
const res = await fetch(`${addr}/roles/${id}`, {
credentials: 'include',
})
if (res.ok) {
return res.json() as Promise<Role>;
} else {
throw new Error("Could not load role");
}
}
export async function getRoleMembers(id: number): Promise<MemberLight[]> {
const res = await fetch(`${addr}/roles/${id}/members`, {
credentials: 'include',
})
if (res.ok) {
return res.json();
} else {
throw new Error("Could not load members");
}
}
export async function createRole(name: string, color: string, description: string | null): Promise<Role | null> {
const res = await fetch(`${addr}/roles`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
credentials: 'include',
body: JSON.stringify({
name,
color,
description
}),
});
if (res.ok) {
return res.json() as Promise<Role>;
} else {
console.error("Something went wrong creating the role");
return null;
}
}
export async function addMemberToRole(member_id: number, role_id: number): Promise<boolean> {
const res = await fetch(`${addr}/memberRoles`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
credentials: 'include',
body: JSON.stringify({
member_id,
role_id
})
});
if (res.ok) {
return true;
} else {
console.error("Something went wrong adding the member to the role");
return false;
}
}
export async function removeMemberFromRole(member_id: number, role_id: number): Promise<boolean> {
const res = await fetch(`${addr}/memberRoles`, {
method: "DELETE",
credentials: 'include',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
member_id,
role_id
})
});
if (res.ok) {
return true;
} else {
console.error("Something went wrong removing the member from the role");
return false;
}
}
export async function deleteRole(role_id: number): Promise<boolean> {
const res = await fetch(`${addr}/roles/${role_id}`, {
method: "DELETE",
credentials: 'include',
});
if (res.ok) {
return true;
} else {
console.error("Something went wrong deleting the role");
return false;
}
}