ApiService.ts 1.38 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
13
    generateCalendarUrl = (crns: string[]): string => `${this.apiRoot}/schedules?crns=${crns.join(',')}`;
    openCalendarAsWebcal = (crns: string[]) => {
14
        window.open(`${this.webcalUrl}/schedules?crns=${crns.join(',')}`, '_self');
15
16
17
    };
    fetchICal = async (crns: string[]): Promise<string> =>
        fetch(this.generateCalendarUrl(crns)).then(response => response.text());
18
19
20
}

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

30
const local = 'localhost:3000/api';
31
const remote = `${window.location.hostname}/api`;
32
33
34
35
36

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);