processData.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { randomUUID } from "crypto";
  2. import Logs from "./logs.js";
  3. class ProcessData {
  4. #process;
  5. #name;
  6. #request = {
  7. callbacks: {},
  8. functions: {}
  9. };
  10. #response = {
  11. functions: {}
  12. };
  13. constructor(processInstance = process, name = 'process', showStdout = false) {
  14. this.#process = processInstance;
  15. this.#name = name;
  16. this.#process.on('message', (message) => {
  17. this.#handleMessage(message);
  18. });
  19. this.#process.stdout?.on('data', data => {
  20. if (showStdout) {
  21. Logs.out('%s stdout: ↩︎', name);
  22. console.log(data.toString());
  23. }
  24. });
  25. this.#process.stderr?.on('data', data => {
  26. Logs.out('%s stderr', name, data.toString());
  27. });
  28. }
  29. get(type, params) {
  30. const id = randomUUID();
  31. this.#process.send({ method: 'get', type, id, params });
  32. return new Promise(resolve => {
  33. this.#request.callbacks[id] = resolve;
  34. });
  35. }
  36. registerResponse(type, func) {
  37. this.#response.functions[type] = func;
  38. }
  39. #responseData(type, params, id) {
  40. const func = this.#response.functions[type];
  41. func?.(params).then(data => {
  42. this.#process.send({ type: 'response', data, id });
  43. });
  44. }
  45. post(type, data) {
  46. this.#process.send({ method: 'post', type, data });
  47. }
  48. registerRequest(type, func) {
  49. this.#request.functions[type] = func;
  50. }
  51. #requestData(type, data) {
  52. const func = this.#request.functions[type];
  53. func?.(data);
  54. }
  55. #handleMessage(message) {
  56. const { callbacks } = this.#request;
  57. const { method, type, data, error, id, params } = message;
  58. if (error) {
  59. console.error(error);
  60. }
  61. if (method == 'get' && id) {
  62. this.#responseData(type, params, id);
  63. }
  64. else if (type == 'response' && id && callbacks[id]) {
  65. callbacks[id](data);
  66. delete callbacks[id];
  67. }
  68. else if (method == 'post' && type) {
  69. this.#requestData(type, data);
  70. }
  71. }
  72. }
  73. export default ProcessData;