Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save MacKentoch/d003b9540d5eeac556df0efa64449f99 to your computer and use it in GitHub Desktop.

Select an option

Save MacKentoch/d003b9540d5eeac556df0efa64449f99 to your computer and use it in GitHub Desktop.
import {
getLocationOrigin
} from '../fetchTools';
const BASE_URL = getLocationOrigin();
export const promisedHttpRequest = (endpoint, options, onProgressCallback) => {
request('GET', `${BASE_URL}/${endpoint}`, options, onProgressCallback);
};
function request(url, opts = {}, onProgress) {
return new Promise(
(res, rej) => {
const xhr = new XMLHttpRequest();
xhr.open(opts.method || 'get', url);
Object
.keys(opts.headers || {})
.forEach(
headerKey => {
xhr.setRequestHeader(headerKey, opts.headers[headerKey]);
}
);
xhr.onload = e => res(e.target.responseText);
xhr.onerror = rej;
if (xhr.upload && onProgress) {
xhr.upload.onprogress = onProgress; // event.loaded / event.total * 100 ; //event.lengthComputable
}
xhr.send(opts.body);
}
);
}
@rizrmd

rizrmd commented Jul 11, 2021

Copy link
Copy Markdown

This is typescript version:

function request(
  url: string,
  opts: {
    method?: 'get' | 'post'
    headers?: any
    body?: Parameters<XMLHttpRequest['send']>[0]
  } = {},
  onProgress: XMLHttpRequest['upload']['onprogress']
) {
  return new Promise((res, rej) => {
    const xhr = new XMLHttpRequest()
    xhr.open(opts.method || 'get', url)

    Object.keys(opts.headers || {}).forEach((headerKey) => {
      xhr.setRequestHeader(headerKey, opts.headers[headerKey])
    })

    xhr.onload = (e: any) => res(e.target.responseText)

    xhr.onerror = rej

    if (xhr.upload && onProgress) {
      xhr.upload.onprogress = onProgress // event.loaded / event.total * 100 ; //event.lengthComputable
    }

    xhr.send(opts.body)
  })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment