garmsync garmsync
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.

55 lines
1.5 KiB

11 months ago
  1. export default class Trimlog {
  2. constructor({username, password}) {
  3. this.token = null;
  4. this.tokenExpiry = new Date(0);
  5. this.username = username;
  6. this.password = password;
  7. }
  8. async getLooseActivities() {
  9. return this.fetch("GET", "activities");
  10. }
  11. async getWorkouts() {
  12. return this.fetch("GET", `workouts?from=${new Date(Date.now() - 86400000 * 3).toISOString().slice(0, 10)}`);
  13. }
  14. async postWorkout(data) {
  15. return this.fetch("POST", "workouts", data);
  16. }
  17. async fetch(method, path, body) {
  18. if (new Date() > this.tokenExpiry) {
  19. await this.refreshToken();
  20. }
  21. const res = await fetch("https://i.stifred.dev/api/"+path, {
  22. method: method,
  23. headers: {
  24. "content-type": body ? "application/json" : void(0),
  25. "authorization": `Bearer ${this.token}`
  26. },
  27. body: body ? JSON.stringify(body) : void(0),
  28. })
  29. if (!res.ok) {
  30. throw new Error(res.statusText);
  31. }
  32. return (await res.json()).data;
  33. }
  34. async refreshToken() {
  35. const res = await fetch("https://stifred.auth.eu-west-1.amazoncognito.com/oauth2/token", {
  36. method: "POST",
  37. headers: {
  38. "content-type": "application/x-www-form-urlencoded",
  39. "authorization": `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`
  40. },
  41. body: "grant_type=client_credentials&scope=indigo/api",
  42. })
  43. const data = await res.json();
  44. this.token = data.access_token;
  45. this.tokenExpiry = new Date(Date.now() + (data.expires_in * 1000 * 0.95));
  46. }
  47. }