A cleaner approach to the cancel command

This commit is contained in:
Rafa de la Torre 2018-06-04 16:34:37 +02:00
parent 4022fb2967
commit 014ea8142b

View File

@ -16,6 +16,9 @@ module.exports = {
} }
let responseEnded = false; let responseEnded = false;
let connectionClosedByClient = false;
const copyToStream = copyTo(sql);
const pgstream = client.query(copyToStream);
res res
.on('error', err => { .on('error', err => {
@ -25,28 +28,26 @@ module.exports = {
}) })
.on('close', () => { .on('close', () => {
if (!responseEnded) { if (!responseEnded) {
// Cancel the running COPY TO query. connectionClosedByClient = true;
// Cancel the running COPY TO query
// See https://www.postgresql.org/docs/9.5/static/protocol-flow.html#PROTOCOL-COPY // See https://www.postgresql.org/docs/9.5/static/protocol-flow.html#PROTOCOL-COPY
const runningClient = client; const runningClient = client;
const cancelingClient = new Client(runningClient.connectionParameters); const cancelingClient = new Client(runningClient.connectionParameters);
const connection = cancelingClient.connection; cancelingClient.cancel(runningClient, pgstream);
connection.on('connect', () => { pgstream.unpipe(res);
connection.cancel(runningClient.processID, runningClient.secretKey); done(new Error('Connection closed by client'));
done(); return cb(err);
});
connection.connect(runningClient.port, runningClient.host);
return cb(new Error('Connection closed by client'));
} }
}) })
.on('end', () => responseEnded = true); .on('end', () => responseEnded = true);
const copyToStream = copyTo(sql);
const pgstream = client.query(copyToStream);
pgstream pgstream
.on('error', err => { .on('error', err => {
pgstream.unpipe(res); if (!connectionClosedByClient) {
done(); pgstream.unpipe(res);
return cb(err); done(new Error('Connection closed by client'));
return cb(err);
}
}) })
.on('data', data => metrics.addSize(data.length)) .on('data', data => metrics.addSize(data.length))
.on('end', () => { .on('end', () => {