webconsole/src/components/api.ts

82 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-01-18 11:47:11 +00:00
class ApiController {
token: string;
apiurl: string;
2022-01-21 00:55:32 +00:00
2022-01-18 11:47:11 +00:00
async getApiurl() {
let response = await fetch(`${window.location.href}apiurl`)
2022-01-21 09:16:03 +00:00
if(await response.ok) {
this.apiurl = await response.text();
console.log(this.apiurl);
} else {
console.log("Failed to get apiurl");
}
2022-01-18 11:47:11 +00:00
}
2022-01-21 00:55:32 +00:00
async login(username: string , password: string) {
2022-01-21 09:16:03 +00:00
let promise = await fetch(`http://localhost:8000/token/`, {
2022-01-18 11:47:11 +00:00
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
2022-01-21 09:16:03 +00:00
"accept": "application/json",
"access-control-allow-origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Credentials": "true",
2022-01-18 11:47:11 +00:00
},
body: new URLSearchParams({
2022-01-21 00:55:32 +00:00
username: username,
password: password
2022-01-18 11:47:11 +00:00
})
});
2022-01-21 09:16:03 +00:00
if(await promise.ok) {
2022-01-18 11:47:11 +00:00
this.token = (await promise.json())['access_token'];
console.log(this.token);
2022-01-21 09:16:03 +00:00
} else {
console.log("Failed to login");
2022-01-18 11:47:11 +00:00
}
}
2022-01-21 00:55:32 +00:00
async get(path) {
2022-01-21 09:16:03 +00:00
console.log(this.token);
2022-01-21 00:55:32 +00:00
let promise = await fetch(`${this.apiurl}${path}/`, {
method: "GET",
headers: {
"accept": "application/json",
"Authorization": `Bearer ${this.token}`,
2022-01-21 09:16:03 +00:00
"Access-Control-Allow-Origin": "http://localhost:8000",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Credentials": "true",
2022-01-21 00:55:32 +00:00
}
});
2022-01-21 09:16:03 +00:00
if(await promise.ok) {
2022-01-21 00:55:32 +00:00
let data = await promise.json();
return data;
}
2022-01-18 11:47:11 +00:00
}
2022-01-21 09:16:03 +00:00
async post(path){
let promise = await fetch(`${this.apiurl}${path}/`, {
method: "POST",
2022-01-21 00:55:32 +00:00
headers: {
2022-01-21 09:16:03 +00:00
"accept": "application/json",
"Authorization": `Bearer ${this.token}`,
"Access-Control-Allow-Origin": "http://localhost:8000",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Credentials": "true",
}
2022-01-21 00:55:32 +00:00
});
2022-01-21 09:16:03 +00:00
if(await promise.ok) {
2022-01-21 00:55:32 +00:00
let data = await promise.json();
2022-01-21 09:16:03 +00:00
return data;
2022-01-21 00:55:32 +00:00
}
2022-01-21 09:16:03 +00:00
2022-01-18 11:47:11 +00:00
}
2022-01-21 00:55:32 +00:00
2022-01-18 11:47:11 +00:00
}
export const Api = new ApiController();