gpm.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { parseJSON, parseStatus, userFeedbackError } from './response';
  2. import { config } from 'grav-config';
  3. import { EventEmitter } from 'events';
  4. export default class GPM extends EventEmitter {
  5. constructor(action = 'getUpdates') {
  6. super();
  7. this.payload = {};
  8. this.raw = {};
  9. this.action = action;
  10. }
  11. setPayload(payload = {}) {
  12. this.payload = payload;
  13. this.emit('payload', payload);
  14. return this;
  15. }
  16. setAction(action = 'getUpdates') {
  17. this.action = action;
  18. this.emit('action', action);
  19. return this;
  20. }
  21. fetch(callback = () => true, flush = false) {
  22. let data = new FormData();
  23. data.append('admin-nonce', config.admin_nonce);
  24. if (flush) {
  25. data.append('flush', true);
  26. }
  27. this.emit('fetching', this);
  28. fetch(`${config.base_url_relative}/update.json/task${config.param_sep}getUpdates`, {
  29. credentials: 'same-origin',
  30. method: 'post',
  31. body: data
  32. }).then((response) => { this.raw = response; return response; })
  33. .then(parseStatus)
  34. .then(parseJSON)
  35. .then((response) => this.response(response))
  36. .then((response) => callback(response, this.raw))
  37. .then((response) => this.emit('fetched', this.payload, this.raw, this))
  38. .catch(userFeedbackError);
  39. }
  40. response(response) {
  41. this.payload = response;
  42. return response;
  43. }
  44. }
  45. export let Instance = new GPM();