Agent.js 1.2 KB

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