All files / src http-request.js

93.44% Statements 57/61
87.5% Branches 14/16
85.71% Functions 6/7
93.44% Lines 57/61

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 621x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
const     attr = (el, attr)=> el.getAttribute(attr);
 
export class HttpRequestElement extends HTMLElement
{
    // @attribute url
    constructor() {
        super();
    }
    get requestHeaders()
    {   const ret = {};
        [...this.attributes].filter(a=>a.name.startsWith('header-')).map( a => ret[a.name.substring(7)] = a.value );
        return ret;
    }
    get requestProps()
    {   const ret = {};
        [...this.attributes].filter(a=>!a.name.startsWith('header-')).map( a => ret[a.name] = a.value );
        return ret;
    }
    sliceInit( s )
    {   if( !s )
            s = {};
        s.element = this;
        if( s.destroy )
            return s;
        const controller = new AbortController();
        s.destroy = ()=>
        {   // todo destroy slices in custom-element
            controller.abort();
        };
        const     url = attr(this, 'url') || ''
        ,     request = { ...this.requestProps, headers: this.requestHeaders }
        ,       slice = { detail: { request }, target: this }
        , updateSlice = slice =>
        {   for( let parent = s.element.parentElement; parent; parent = parent.parentElement )
                if ( parent.onSlice )
                    return parent.onSlice(slice);
            console.error(`${this.localName} used outside of custom-element`)
            debugger;
        };
 
        setTimeout( async ()=>
        {   updateSlice( slice );
            const response = await fetch(url,{ ...this.requestProps, signal: controller.signal, headers: this.requestHeaders })
            ,      r= {headers: {}};
            [...response.headers].map( ([k,v]) => r.headers[k]=v );
            'ok,status,statusText,type,url,redirected'.split(',').map(k=>r[k]=response[k])
 
            slice.detail.response = r;
            updateSlice( slice );
            const detail = {...slice.detail}
            detail.data = await response.json();
            const s = {...slice, detail}
            updateSlice( s );
        },0 );
 
        return s;
    }
}
 
window.customElements.define( 'http-request', HttpRequestElement );
export default HttpRequestElement;