api.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * xhr.status ---> fail
  3. * response.code === 0 ---> success
  4. * response.code !== 0 ---> error
  5. * */
  6. const SendXMLHttpRequest = (url, data, success, error, fail) => {
  7. const xhr = new XMLHttpRequest();
  8. xhr.onreadystatechange = () => {
  9. if (xhr.readyState === 4) {
  10. if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
  11. const response = JSON.parse(xhr.responseText);
  12. if (response.code !== 0) {
  13. return error(xhr, response);
  14. }
  15. return success(xhr, response);
  16. }
  17. fail(xhr);
  18. }
  19. };
  20. xhr.open(data !== null ? 'POST' : 'GET', url, true);
  21. xhr.send(data !== null ? JSON.stringify(data) : null);
  22. };
  23. export default {
  24. send: (endpoint, danmakuData, callback) => {
  25. SendXMLHttpRequest(endpoint, danmakuData, (xhr, response) => {
  26. console.log('Post danmaku: ', response);
  27. if (callback) {
  28. callback();
  29. }
  30. }, (xhr, response) => {
  31. alert(response.msg);
  32. }, (xhr) => {
  33. console.log('Request was unsuccessful: ' + xhr.status);
  34. });
  35. },
  36. read: (endpoint, callback) => {
  37. SendXMLHttpRequest(endpoint, null, (xhr, response) => {
  38. callback(null, response.danmaku);
  39. }, (xhr, response) => {
  40. callback({ status: xhr.status, response });
  41. }, (xhr) => {
  42. callback({ status: xhr.status, response: null });
  43. });
  44. }
  45. };