Agent.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @author oldj
  3. * @blog https://oldj.net
  4. */
  5. 'use strict'
  6. const IS_DEV = process.env.ENV === 'dev'
  7. const {ipcRenderer} = require('electron')
  8. const platform = process.platform
  9. ipcRenderer.setMaxListeners(20)
  10. const EventEmitter = require('events')
  11. class MyEmitter extends EventEmitter {}
  12. const evt = new MyEmitter();
  13. let x_get_idx = 0
  14. /**
  15. * act
  16. * @param action {String}
  17. * @param [data] {Any}
  18. * @param callback {Function}
  19. */
  20. function act (action, data, callback) {
  21. let fn = ['_cb', (new Date()).getTime(), (x_get_idx++)].join('_')
  22. if (!callback && typeof data === 'function') {
  23. callback = data
  24. data = null
  25. }
  26. if (typeof callback === 'function') {
  27. ipcRenderer.once(fn, (e, d) => callback.apply(null, d))
  28. }
  29. ipcRenderer.send('x', {
  30. action
  31. , data
  32. , callback: fn
  33. })
  34. }
  35. function pact (action, ...args) {
  36. return new Promise((resolve, reject) => act(action, args,
  37. (err, result) => err ? reject(err) : resolve(result)))
  38. }
  39. module.exports = {
  40. IS_DEV
  41. , platform
  42. , act
  43. , pact
  44. , on: (...args) => evt.on(...args)
  45. , emit: (...args) => evt.emit(...args)
  46. }