ApiService.ts 1.13 KB
Newer Older
1
2
class ApiService {
    private apiRoot: string;
3
    private webcalUrl: string;
4

5
    public constructor(apiRoot: string, webcalUrl: string) {
6
        this.apiRoot = apiRoot;
7
        this.webcalUrl = webcalUrl;
8
9
    }

Zac Wood's avatar
Zac Wood committed
10
    searchCourseSections = async (crn: string): Promise<any[]> =>
11
        fetchJson(`${this.apiRoot}/course_sections?crn=${crn}`);
12
    subscribeToCalendar = (crns: string[]) =>
13
        window.open(`${this.webcalUrl}/schedules?crns=${crns.join(',')}`, '_self');
14
15
16
}

const fetchJson = async (url: string): Promise<any> => fetch(url).then(response => response.json());
17
18
19
20
21
22
23
24
const postJson = (endpoint: string, data: any): Promise<Response> =>
    fetch(endpoint, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json',
        },
    });
25

26
const local = 'localhost:3000/api';
Zac Wood's avatar
Zac Wood committed
27
const remote = `${window.location.hostname}/api`
28
29
30
31
32

const apiUrl = process.env.NODE_ENV === 'development' ? `http://${local}` : `https://${remote}`;
const webcalUrl = process.env.NODE_ENV === 'development' ? `webcal://${local}` : `webcal://${remote}`;

export default new ApiService(apiUrl, webcalUrl);