import { validate } from './properties' ; /** Namespace that comprises various utils (also cleans up documentation). */ namespace fetch { const failed = ( url , request ) => `fetching '${ url }' failed (${ request . status }): ${ request . statusText }` ; export interface FetchTransform < T > { ( data ) : T | undefined ; } param url param type returns export function fetchAsync < T > ( url , type ) { const response = new Promise < T > ( ( resolve , reject ) => { const request = new XMLHttpRequest ( ) ; request . open ( 'GET' , url , true ) ; request . responseType = type ; request . onload = ( ) => { if ( request . status < 200 || request . status >= 300 ) { reject ( failed ( url , request ) ) ; return ; } resolve ( request . response ) ; } ; request . onerror = ( ) => reject ( failed ( url , request ) ) ; request . ontimeout = ( ) => reject ( failed ( url , request ) ) ; request . send ( ) ; } ) ; return response ; } param url param transform param schema returns export function fetchJsonAsync < T > ( url , transform , schema ? ) { const response = new Promise < T > ( ( resolve , reject ) => { const request = new XMLHttpRequest ( ) ; request . open ( 'GET' , url , true ) ; request . onload = ( ) => { if ( request . status < 200 || request . status >= 300 ) { reject ( failed ( url , request ) ) ; return ; } const json = request . responseText ; if ( schema !== undefined && ! validate ( json , schema ) ) { return ; } let data ; try { data = JSON . parse ( json ) ; } catch ( error ) { reject ( `fetching '${ url }' failed (${ error . name }): ${ error . message }` ) ; return ; } const object = transform ( data ) ; if ( object === undefined ) { reject ( `fetching '${ url }' failed (TransformError): transforming the object failed.` ) ; return ; } resolve ( object ) ; } ; request . onerror = ( ) => reject ( failed ( url , request ) ) ; request . ontimeout = ( ) => reject ( failed ( url , request ) ) ; request . send ( ) ; } ) ; return response ; } } export = fetch ;