All files / mframejs/utils fetchClient.ts

7.14% Statements 1/14
0% Branches 0/19
0% Functions 0/4
7.14% Lines 1/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90          29x                                                                                                                                                                        
import { IFetchConfig } from '../interface/exported';
/**
 * Very simple fetch helper
 * https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
 */
export class FetchClient {
 
 
    constructor(private config = {} as IFetchConfig) {
        this.setConfig(config);
    }
 
 
 
    /**
     * setConfig
     *
     */
    public setConfig(config: IFetchConfig) {
        if (config.defaultUrl) {
            this.config.defaultUrl = config.defaultUrl;
        }
 
        if (config.cache) {
            this.config.cache = config.cache;
        }
 
        if (config.credentials) {
            this.config.credentials = config.credentials;
        }
 
        if (config.headers) {
            this.config.headers = config.headers;
        }
 
        if (config.method) {
            this.config.method = config.method;
        }
 
        if (config.mode) {
            this.config.mode = config.mode;
        }
 
        if (config.redirect) {
            this.config.redirect = config.redirect;
        }
 
        if (config.referrer) {
            this.config.referrer = config.referrer;
        }
    }
 
 
 
    /**
     * getconfig
     *
     */
    public getConfig() {
        return this.config;
    }
 
 
 
    /**
     * fetch
     *
     */
    public fetch(url: string, options: IFetchConfig): Promise<any> {
        const fetchUrl =
            this.config.defaultUrl ? this.config.defaultUrl + url : url;
        const fetchOptions: any = {
            body: options.body ? options.body : undefined,
            cache: options.cache || this.config.cache,
            credentials: options.credentials || this.config.credentials,
            headers: options.headers || this.config.headers,
            method: options.method || this.config.method,
            mode: options.mode || this.config.mode,
            redirect: options.redirect || this.config.redirect,
            referrer: options.referrer || this.config.referrer
        };
 
        return fetch(fetchUrl, (fetchOptions as any));
    }
 
 
}