~starkingdoms/starkingdoms

ref: 297f290ad7f583d8e2cfbdd18630df88d121142e starkingdoms/starkingdoms-client/src/config.ts -rw-r--r-- 1.2 KiB
297f290a — core add license and config system 2 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import createDebug from "debug";
import CONFIG from "./config.json";

const logger = createDebug("config");

const CONFIG_URL = "https://configuration.starkingdoms.io";

export interface Config {
    servers: {[id: string]: ConfigServer}
}
export interface ConfigServer {
    name: string;
    clientHubUrl: string;
    apiBaseUrl: string;
    isProduction: boolean;
    isDevelopment: boolean;
    isPrimary: boolean;
}

async function fetchWithTimeout(resource: RequestInfo | URL, options = {}) {
    // @ts-ignore
    const { timeout = 8000 } = options;

    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), timeout);

    const response = await fetch(resource, {
        ...options,
        signal: controller.signal
    });
    clearTimeout(id);

    return response;
}

export async function loadConfig(): Promise<Config> {
    logger("loading configuration from " + CONFIG_URL);
    try {
        const response = await fetchWithTimeout(CONFIG_URL, {
            timeout: 1000
        });
        return await response.json();
    } catch (e) {
        logger(`error loading configuration: ${e}, using fallback`);
        // @ts-ignore strong types are unhelpful here
        return CONFIG;
    }
}