api.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const cache = {}
  2. let initialized = false
  3. const proxy = new Proxy({
  4. __consume () {
  5. for (const key in cache) {
  6. if (key in window.tauri) {
  7. const queue = cache[key]
  8. for (const call of queue) {
  9. try {
  10. const ret = window.tauri[key].apply(window.tauri, call.arguments)
  11. if (ret instanceof Promise) {
  12. ret.then(call.resolve, call.reject)
  13. } else {
  14. call.resolve()
  15. }
  16. } catch (e) {
  17. call.reject(e)
  18. }
  19. }
  20. }
  21. }
  22. initialized = true
  23. }
  24. }, {
  25. get (obj, prop) {
  26. if (prop === '__consume') {
  27. return obj[prop]
  28. }
  29. if (initialized && 'tauri' in window) {
  30. return window.tauri[prop].bind(window.tauri)
  31. }
  32. if (!(prop in cache)) {
  33. cache[prop] = []
  34. }
  35. return function () {
  36. const promise = new Promise((resolve, reject) => {
  37. cache[prop].push({
  38. arguments: arguments,
  39. resolve,
  40. reject
  41. })
  42. });
  43. return promise;
  44. }
  45. }
  46. })
  47. window.onTauriInit = () => {
  48. proxy.__consume()
  49. }
  50. export default proxy