atomicQuery.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * Used to send a notification message to the host
  3. * @param {string} messageType
  4. * @param {object} data
  5. * @return {Promise} will resolve when the host has handled the message
  6. */
  7. function atomicHostEvent(messageType, data) {
  8. let queryMessage;
  9. // if we have a data element, then we need to structure the message so that the host understands it
  10. // by adding the message to the object and then stringify-ing the whole thing
  11. if (data) {
  12. // stringify and reparse since we need to modify the data, but don't want to modify the passed in object
  13. queryMessage = JSON.parse(JSON.stringify(data));
  14. queryMessage.message = messageType;
  15. } else {
  16. queryMessage = {
  17. message
  18. };
  19. }
  20. return new Promise((resolve, reject) => {
  21. window.atomicQuery({
  22. request: JSON.stringify(queryMessage),
  23. persistent: true,
  24. onSuccess: (result) => resolve(),
  25. onFailure: (error_code, error_message) => {
  26. console.log(error_code);
  27. console.log(error_message);
  28. reject({ error_code, error_message });
  29. }
  30. });
  31. });
  32. }
  33. /**
  34. * Used to send a request to the server. The server will send back the results in the promise
  35. * @param {string} messageType
  36. * @param {object} data
  37. * @return {Promise}
  38. */
  39. function atomicHostRequest(messageType, data) {
  40. let queryMessage;
  41. // if we have a data element, then we need to structure the message so that the host understands it
  42. // by adding the message to the object and then stringify-ing the whole thing
  43. if (data) {
  44. // stringify and reparse since we need to modify the data, but don't want to modify the passed in object
  45. queryMessage = JSON.parse(JSON.stringify(data));
  46. queryMessage.message = messageType;
  47. } else {
  48. queryMessage = {
  49. message
  50. };
  51. }
  52. return new Promise((resolve, reject) => {
  53. window.atomicQuery({
  54. request: JSON.stringify(queryMessage),
  55. persistent: false,
  56. onSuccess: (s) => {
  57. // unwrap the message that was returned
  58. let o = JSON.parse(s);
  59. resolve(o);
  60. },
  61. onFailure: (error_code, error_message) => reject({ error_code, error_message })
  62. });
  63. });
  64. }