~sirn/fanboi2

ref: a68873a108d20a6a49a1b6caf374bfb2cf6a94fe fanboi2/assets/app/javascripts/utils/request.ts -rw-r--r-- 783 bytes
a68873a1Kridsada Thanabulpong Coding style cleanups and setup pre-commit hooks (#42) 3 years ago
                                                                                
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
import { CancellableToken, Cancelled } from "./cancellable";

export interface IRequestBody {
    [key: string]: any;
}

export const request = (
    method: string,
    url: string,
    params: IRequestBody = {},
    token?: CancellableToken,
): Promise<string> => {
    let xhr = new XMLHttpRequest();
    let body = JSON.stringify(params);

    xhr.open(method, url);
    xhr.setRequestHeader("Content-Type", "application/json");

    return new Promise((resolve, reject) => {
        xhr.onload = () => {
            resolve(xhr.responseText);
        };
        xhr.onerror = reject;

        if (token) {
            token.cancel = (): void => {
                xhr.abort();
                reject(new Cancelled());
            };
        }

        xhr.send(body);
    });
};