This repository has been archived by the owner on Aug 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathworkerHelper.ts
97 lines (85 loc) · 2.38 KB
/
workerHelper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { Task, TextEditor } from 'atom';
import type { ConfigSchema } from "./config"
import cryptoRandomString from 'crypto-random-string';
import type * as Tslint from "tslint";
export class WorkerHelper {
workerInstance: Task | null
constructor() {
this.workerInstance = null;
}
isRunning() {
return Boolean(this.workerInstance);
}
startWorker(config: ConfigSchema) {
if (!this.workerInstance) {
this.workerInstance = new Task(require.resolve('./worker.js'));
this.workerInstance.start(config);
}
}
terminateWorker() {
if (this.workerInstance) {
this.workerInstance.terminate();
this.workerInstance = null;
}
}
changeConfig(key: string, value: any) {
if (this.workerInstance) {
this.workerInstance.send({
messageType: 'config',
message: { key, value },
} as ConfigMessage);
}
}
async requestJob(jobType: string, textEditor: TextEditor): Promise<Tslint.LintResult[]> {
if (this.workerInstance === null) {
throw new Error("Worker hasn't started");
}
const emitKey = await cryptoRandomString.async({ length: 10 });
return new Promise((resolve, reject) => {
if (this.workerInstance === null) {
throw new Error("Worker hasn't started");
}
const errSub = this.workerInstance.on('task:error', (...err) => {
// Re-throw errors from the task
const error = new Error(err[0]);
// Set the stack to the one given to us by the worker
[, error.stack] = err;
reject(error);
});
const responseSub = this.workerInstance.on(emitKey, (data: Tslint.LintResult[]) => {
errSub.dispose();
responseSub.dispose();
resolve(data);
});
try {
this.workerInstance.send({
messageType: 'job',
message: {
emitKey,
jobType,
content: textEditor.getText(),
filePath: textEditor.getPath(),
},
} as JobMessage);
} catch (e) {
reject(e);
}
});
}
}
export type ConfigMessage = {
messageType: 'config',
message: {
key: keyof ConfigSchema,
value: boolean | string | null,
}
}
export type JobMessage = {
messageType: 'job',
message: {
emitKey: string,
jobType: string,
content: ReturnType<TextEditor["getText"]>,
filePath: ReturnType<TextEditor["getPath"]>,
}
}