Agent.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. const EventEmitter = require('events')
  10. const evt = new EventEmitter()
  11. const max_listener_count = 20
  12. evt.setMaxListeners(max_listener_count)
  13. ipcRenderer.setMaxListeners(max_listener_count)
  14. let x_get_idx = 0
  15. /**
  16. * act
  17. * @param action {String}
  18. * @param args {Array}
  19. */
  20. function act (action, ...args) {
  21. let fn = ['_cb', (new Date()).getTime(), (x_get_idx++)].join('_')
  22. let callback
  23. if (args.length > 0 && typeof args[args.length - 1] === 'function') {
  24. callback = args.pop()
  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: args
  32. , callback: fn
  33. })
  34. }
  35. function pact (action, ...args) {
  36. return new Promise((resolve, reject) => {
  37. args.push((err, result) => err ? reject(err) : resolve(result))
  38. act(action, ...args)
  39. })
  40. }
  41. ipcRenderer.on('y', (sender, d) => {
  42. evt.emit(d.event, ...d.data || [])
  43. })
  44. module.exports = {
  45. IS_DEV
  46. , platform
  47. , act
  48. , pact
  49. , on: (...args) => evt.on(...args)
  50. , emit: (...args) => evt.emit(...args)
  51. }