aboutsummaryrefslogtreecommitdiff
path: root/src/client/Network.ts
blob: a222b320f69604c224c63f56f13925c9c71f3412 (plain)
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
import { Utils } from '../Utils';
import requestPromise = require('request-promise');
import { Upload } from '../server/SharedMediaTypes';

export namespace Networking {
    export async function FetchFromServer(relativeRoute: string) {
        return (await fetch(relativeRoute)).text();
    }

    export async function PostToServer(relativeRoute: string, body?: any) {
        const options = {
            uri: Utils.prepend(relativeRoute),
            method: 'POST',
            body,
            json: true,
        };
        return requestPromise.post(options);
    }

    /**
     * Handles uploading basic file types to server and makes the API call to "/uploadFormData" endpoint
     * with the mapping of GUID to filem as parameters.
     *
     * @param files the files to be uploaded to the server
     * @returns the response as a json from the server
     */
    export async function UploadFilesToServer<T extends Upload.FileInformation = Upload.FileInformation>(files: File | File[]): Promise<Upload.FileResponse<T>[]> {
        const formData = new FormData();
        if (Array.isArray(files)) {
            if (!files.length) {
                return [];
            }
            files.forEach(file => formData.append(Utils.GenerateGuid(), file));
        } else {
            formData.append(Utils.GenerateGuid(), files);
        }
        const parameters = {
            method: 'POST',
            body: formData,
        };
        const response = await fetch('/uploadFormData', parameters);
        return response.json();
    }

    export async function UploadYoutubeToServer<T extends Upload.FileInformation = Upload.FileInformation>(videoId: string): Promise<Upload.FileResponse<T>[]> {
        const parameters = {
            method: 'POST',
            body: JSON.stringify({ videoId }),
            json: true,
        };
        const response = await fetch('/uploadYoutubeVideo', parameters);
        return response.json();
    }
}