This repository was archived by the owner on Mar 15, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathApiResult.ts
58 lines (57 loc) · 1.75 KB
/
ApiResult.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
import { ChildProcess } from 'child_process';
import { Readable } from 'stream';
export class ApiResult {
private apiProcess: ChildProcess;
private output: Promise<string>;
private statusCode: Promise<number>;
private apiRunning: boolean;
constructor(apiProcess: ChildProcess) {
this.apiRunning = true;
this.apiProcess = apiProcess;
this.output = this.readStream(this.apiProcess.stdout);
this.statusCode = this.readStatusCode();
}
public async getStatusCode(): Promise<number> {
return await this.statusCode;
}
public isRunning(): boolean {
return this.apiRunning;
}
public async getOutputObject(): Promise<Object> {
let output = await this.output;
try {
return JSON.parse(output);
} catch (e) {
console.error(e);
throw e;
}
}
public async getOutputString(): Promise<string> {
return await this.output;
}
public killApi(): void {
this.apiProcess.kill('SIGHUP');
}
private async readStatusCode(): Promise<number> {
return new Promise<number>(resolve => {
this.apiProcess.on('close', code => {
this.apiRunning = false;
resolve(code);
});
});
}
private async readStream(stream: Readable): Promise<string> {
return new Promise<string>((resolve, reject) => {
let data = [];
stream.on('data', (chunk) => {
data.push(chunk);
});
stream.on('end', () => {
resolve(Buffer.concat(data).toString());
});
stream.on('error', (error) => {
reject(error);
});
});
}
}