(process: NodeJS.Process, msgHandler: d.WorkerMsgHandler)
| 9 | * messages |
| 10 | */ |
| 11 | export const initNodeWorkerThread = (process: NodeJS.Process, msgHandler: d.WorkerMsgHandler) => { |
| 12 | const sendHandle = (err: NodeJS.ErrnoException) => { |
| 13 | if (err && err.code === 'ERR_IPC_CHANNEL_CLOSED') { |
| 14 | process.exit(0); |
| 15 | } |
| 16 | }; |
| 17 | |
| 18 | const errorHandler = (stencilMsgId: number, err: any) => { |
| 19 | const errMsgBackToMain: d.MsgFromWorker<any> = { |
| 20 | stencilId: stencilMsgId, |
| 21 | stencilRtnValue: null, |
| 22 | stencilRtnError: 'Error', |
| 23 | }; |
| 24 | if (typeof err === 'string') { |
| 25 | errMsgBackToMain.stencilRtnError += ': ' + err; |
| 26 | } else if (err) { |
| 27 | if (err.stack) { |
| 28 | errMsgBackToMain.stencilRtnError += ': ' + err.stack; |
| 29 | } else if (err.message) { |
| 30 | errMsgBackToMain.stencilRtnError += ':' + err.message; |
| 31 | } |
| 32 | } |
| 33 | process.send(errMsgBackToMain, sendHandle); |
| 34 | }; |
| 35 | |
| 36 | process.on('message', async <T extends d.WorkerContextMethod>(msgToWorker: d.MsgToWorker<T>) => { |
| 37 | // message from the main thread |
| 38 | if (msgToWorker && typeof msgToWorker.stencilId === 'number') { |
| 39 | try { |
| 40 | // run the handler to get the data |
| 41 | const msgFromWorker: d.MsgFromWorker<T> = { |
| 42 | stencilId: msgToWorker.stencilId, |
| 43 | stencilRtnValue: await msgHandler(msgToWorker), |
| 44 | stencilRtnError: null, |
| 45 | }; |
| 46 | |
| 47 | // send response data from the worker to the main thread |
| 48 | process.send(msgFromWorker, sendHandle); |
| 49 | } catch (e) { |
| 50 | // error occurred while running the task |
| 51 | errorHandler(msgToWorker.stencilId, e); |
| 52 | } |
| 53 | } |
| 54 | }); |
| 55 | |
| 56 | process.on(`unhandledRejection`, (e: any) => { |
| 57 | errorHandler(-1, e); |
| 58 | }); |
| 59 | }; |
no test coverage detected