You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.5 KiB
56 lines
1.5 KiB
export default class Trimlog {
|
|
constructor({username, password}) {
|
|
this.token = null;
|
|
this.tokenExpiry = new Date(0);
|
|
this.username = username;
|
|
this.password = password;
|
|
}
|
|
|
|
async getLooseActivities() {
|
|
return this.fetch("GET", "activities");
|
|
}
|
|
|
|
async getWorkouts() {
|
|
return this.fetch("GET", `workouts?from=${new Date(Date.now() - 86400000 * 3).toISOString().slice(0, 10)}`);
|
|
}
|
|
|
|
async postWorkout(data) {
|
|
return this.fetch("POST", "workouts", data);
|
|
}
|
|
|
|
async fetch(method, path, body) {
|
|
if (new Date() > this.tokenExpiry) {
|
|
await this.refreshToken();
|
|
}
|
|
|
|
const res = await fetch("https://i.stifred.dev/api/"+path, {
|
|
method: method,
|
|
headers: {
|
|
"content-type": body ? "application/json" : void(0),
|
|
"authorization": `Bearer ${this.token}`
|
|
},
|
|
body: body ? JSON.stringify(body) : void(0),
|
|
})
|
|
|
|
if (!res.ok) {
|
|
throw new Error(res.statusText);
|
|
}
|
|
|
|
return (await res.json()).data;
|
|
}
|
|
|
|
async refreshToken() {
|
|
const res = await fetch("https://stifred.auth.eu-west-1.amazoncognito.com/oauth2/token", {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/x-www-form-urlencoded",
|
|
"authorization": `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`
|
|
},
|
|
body: "grant_type=client_credentials&scope=indigo/api",
|
|
})
|
|
const data = await res.json();
|
|
|
|
this.token = data.access_token;
|
|
this.tokenExpiry = new Date(Date.now() + (data.expires_in * 1000 * 0.95));
|
|
}
|
|
}
|