| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- import { randomUUID } from "crypto";
- import Logs from "./logs.js";
- class ProcessData {
- #process;
- #name;
- #request = {
- callbacks: {},
- functions: {}
- };
- #response = {
- functions: {}
- };
- constructor(processInstance = process, name = 'process', showStdout = false) {
- this.#process = processInstance;
- this.#name = name;
- this.#process.on('message', (message) => {
- this.#handleMessage(message);
- });
- this.#process.stdout?.on('data', data => {
- if (showStdout) {
- Logs.out('%s stdout: ↩︎', name);
- console.log(data.toString());
- }
- });
- this.#process.stderr?.on('data', data => {
- Logs.out('%s stderr', name, data.toString());
- });
- }
- get(type, params) {
- const id = randomUUID();
- this.#process.send({ method: 'get', type, id, params });
- return new Promise(resolve => {
- this.#request.callbacks[id] = resolve;
- });
- }
- registerResponse(type, func) {
- this.#response.functions[type] = func;
- }
- #responseData(type, params, id) {
- const func = this.#response.functions[type];
- func?.(params).then(data => {
- this.#process.send({ type: 'response', data, id });
- });
- }
- post(type, data) {
- this.#process.send({ method: 'post', type, data });
- }
- registerRequest(type, func) {
- this.#request.functions[type] = func;
- }
- #requestData(type, data) {
- const func = this.#request.functions[type];
- func?.(data);
- }
- #handleMessage(message) {
- const { callbacks } = this.#request;
- const { method, type, data, error, id, params } = message;
- if (error) {
- console.error(error);
- }
- if (method == 'get' && id) {
- this.#responseData(type, params, id);
- }
- else if (type == 'response' && id && callbacks[id]) {
- callbacks[id](data);
- delete callbacks[id];
- }
- else if (method == 'post' && type) {
- this.#requestData(type, data);
- }
- }
- }
- export default ProcessData;
|