import {Auth} from "firebase/auth"; import {Contact} from "./typeDefinitions"; export const initializeToken = async (auth: Auth) => { try { const user = auth.currentUser; if (user) { const token = await user.getIdToken(); console.log("this is the token###",token); return token; } else { console.error("User is not signed in."); return null; } } catch (error) { console.error("Error initializing token:", error); return null; } }; export class API { private rootURL: string; private auth: Auth; constructor(auth: Auth, type?:string) { if (type === "local") { this.rootURL = "localhost:3006"; } else { this.rootURL = "placemmentt.co.uk"; } this.auth = auth; } async getContact(id: string): Promise { const token = await initializeToken(this.auth); try { const response = await fetch(`${this.rootURL}/api/contacts/getContacts/${id}`, { method: "GET", headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", }, }); return (await response.json()) as Contact; } catch (error) { console.log(error); } return undefined; } async addContact(details:Contact) { const token = await initializeToken(this.auth); try { const response = await fetch(`${this.rootURL}/api/contacts/addContact`, { method: "POST", headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", }, body: JSON.stringify(details ), }); return (await response.json()); } catch (error) { console.log(error); } } async update_contact(id:string, details:Contact, Constraint:string) { const token = await initializeToken(this.auth); try { const response = await fetch(`${this.rootURL}/api/contacts/update/${id}`, { method: "PUT", headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", }, body: JSON.stringify({ details: details, constraint: Constraint, } ), }); return (await response.json()); } catch (error) { console.log(error); } } async delete_contact(contactid:string) { const token = await initializeToken(this.auth); try { const response = await fetch(`${this.rootURL}/api/contacts/delete}`, { headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", }, body: JSON.stringify({ contactid: contactid, } ), }); return (await response.json()); } catch (error) { console.log(error); } } async get_placements(id:string) { const token = await initializeToken(this.auth); try { const response = await fetch(`${this.rootURL}/api/contacts/getPlacements/${id}`, { method: "GET", headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", }, }); return (await response.json()) as Contact; } catch (error) { console.log(error); } return undefined; } }