-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.ts
70 lines (56 loc) · 1.83 KB
/
api.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { jwtDecode } from "jwt-decode";
import { addDays, format } from "date-fns";
import type { Booking, Duration, Workout } from "./types.ts";
const rootUrl = "https://api.stc.se/api";
export type CreateBookingResponse = {
id: number;
name: string;
duration: Duration;
};
export class StcApi {
customerId: string;
constructor(private token: string) {
const customerId = jwtDecode(token).sub;
if (!customerId) {
throw new Error("Customer ID could not be extracted from token");
}
this.customerId = customerId;
}
private getHeaders = () => ({
accept: "application/json",
"user-agent": "STC",
Authorization: `Bearer ${this.token}`,
"Accept-Language": "sv-SE;sv;q=0.9",
});
getWorkouts = async (clubs: string[]) => {
const dateFormat = "y-LL-dd";
const now = new Date();
const workoutsFrom = format(now, dateFormat);
const workoutsTo = format(addDays(now, 10), dateFormat);
const workoutsUrl = `${rootUrl}/v3/workout-sessions?clubIds=${clubs.join(",")}&endDate=${workoutsTo}&startDate=${workoutsFrom}`;
const response = await fetch(workoutsUrl, {
headers: this.getHeaders(),
});
return (await response.json()) as Workout[];
};
getBookings = async () => {
const bookingsUrl = `${rootUrl}/bookings?customerId=${this.customerId}`;
const response = await fetch(bookingsUrl, {
headers: this.getHeaders(),
});
return (await response.json()) as Booking[];
};
createBooking = async (workoutId: number) => {
const url = `${rootUrl}/bookings`;
const data = {
customerId: this.customerId,
workoutSessionId: workoutId,
};
const response = await fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: this.getHeaders(),
});
return (await response.json()) as CreateBookingResponse;
};
}