Skip to content

Commit 1787d67

Browse files
committed
Improve shutdown: better error handling & move to the REST API
1 parent 42717d3 commit 1787d67

File tree

1 file changed

+15
-21
lines changed

1 file changed

+15
-21
lines changed

src/stop-server.ts

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -43,21 +43,21 @@ function softShutdown(token: string) {
4343

4444
// To handle all this, we send a HTTP request to the GraphQL API instead, which triggers the same thing.
4545
return new Promise<void>((resolve, reject) => {
46-
const req = http.request("http://127.0.0.1:45457", {
46+
const req = http.request("http://127.0.0.1:45457/shutdown", {
4747
method: 'POST',
4848
headers: {
49-
'content-type': 'application/json',
5049
'origin': 'https://app.httptoolkit.tech',
5150
'authorization': `Bearer ${token}`
5251
}
5352
});
54-
req.on('error', reject);
55-
56-
req.end(JSON.stringify({
57-
operationName: 'Shutdown',
58-
query: 'mutation Shutdown { shutdown }',
59-
variables: {}
60-
}));
53+
req.on('error', (e) => {
54+
console.warn(`Error requesting server shutdown: ${e.message}`);
55+
// This often happens - not totally clear why, but seems likely that in the race to
56+
// shut down, the server doesn't successfully send a response first. If the server
57+
// is not reachable though, it's probably shut down already so we're all good.
58+
resolve();
59+
});
60+
req.end();
6161

6262
req.on('response', (res) => {
6363
if (res.statusCode !== 200) {
@@ -71,20 +71,14 @@ function softShutdown(token: string) {
7171
res.on('end', () => {
7272
const rawResponseBody = Buffer.concat(responseChunks);
7373
try {
74-
const responseBody = JSON.parse(rawResponseBody.toString('utf8'));
75-
const errors = responseBody.errors as Array<{ message: string, path: string[] }> | undefined;
76-
if (errors?.length) {
77-
console.error(errors);
78-
const errorCount = errors.length > 1 ? `s (${errors.length})` : '';
74+
const responseBodyString = rawResponseBody.toString('utf8');
75+
const responseBody = JSON.parse(responseBodyString);
7976

80-
throw new Error(
81-
`Server error${errorCount} during shutdown: ${errors.map(e =>
82-
`${e.message} at ${e.path.join('.')}`
83-
).join(', ')}`
84-
);
77+
if (responseBody.success) {
78+
resolve();
79+
} else {
80+
throw new Error(`Server shotdown failed: ${responseBodyString}`);
8581
}
86-
87-
resolve();
8882
} catch (e) {
8983
reject(e);
9084
}

0 commit comments

Comments
 (0)