request.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { parseStatus, parseJSON, userFeedback, userFeedbackError } from './response';
  2. import { config } from 'grav-config';
  3. let raw;
  4. let request = function(url, options = {}, callback = () => true) {
  5. if (typeof options === 'function') {
  6. callback = options;
  7. options = {};
  8. }
  9. if (options.method && options.method === 'post') {
  10. let data = new FormData();
  11. options.body = Object.assign({ 'admin-nonce': config.admin_nonce }, options.body || {});
  12. Object.keys(options.body).map((key) => data.append(key, options.body[key]));
  13. options.body = data;
  14. }
  15. options = Object.assign({
  16. credentials: 'same-origin',
  17. headers: {
  18. 'Accept': 'application/json'
  19. }
  20. }, options);
  21. return fetch(url, options)
  22. .then((response) => {
  23. raw = response;
  24. return response;
  25. })
  26. .then(parseStatus)
  27. .then(parseJSON)
  28. .then(userFeedback)
  29. .then((response) => callback(response, raw))
  30. .catch(userFeedbackError);
  31. };
  32. export default request;