Skip to content

Commit 5f5e40f

Browse files
committed
Add tests to support deprecated event listeners
1 parent fc36340 commit 5f5e40f

File tree

3 files changed

+51
-4
lines changed

3 files changed

+51
-4
lines changed

lib/client.js

+2-4
Original file line numberDiff line numberDiff line change
@@ -374,10 +374,8 @@ Client.prototype.query = function (config, values, callback) {
374374
}
375375
} else {
376376
query = new Query(config, values, callback)
377-
result = query.callback ? undefined : new global.Promise((resolve, reject) => {
378-
query.once('end', resolve)
379-
query.once('error', reject)
380-
})
377+
query._deprecateListeners()
378+
result = query
381379
}
382380

383381
if (this.binary && !query.binary) {

lib/query.js

+19
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,25 @@ Query.prototype.requiresPreparation = function() {
5353
return this.values.length > 0;
5454
};
5555

56+
Query.prototype.then = function(onSuccess, onFailure) {
57+
return this._getPromise().then(onSuccess, onFailure);
58+
};
59+
60+
Query.prototype.catch = function(callback) {
61+
return this._getPromise().catch(callback);
62+
};
63+
64+
Query.prototype._getPromise = function() {
65+
if (this._promise) return this._promise;
66+
this._promise = new Promise(function(resolve, reject) {
67+
this.once('end', resolve);
68+
this.once('error', reject);
69+
}.bind(this));
70+
return this._promise;
71+
};
72+
73+
Query.prototype._deprecateListeners = function() {
74+
}
5675

5776
//associates row metadata from the supplied
5877
//message with this query object
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const helper = require('./test-helper')
2+
const pg = helper.pg
3+
const suite = new helper.Suite()
4+
5+
suite.test('Query with a callback should still support event-listeners', (done) => {
6+
const client = new pg.Client()
7+
const sink = new helper.Sink(3, 1000, () => {
8+
client.end()
9+
done()
10+
})
11+
client.connect()
12+
const query = client.query('SELECT NOW()', (err, res) => {
13+
sink.add()
14+
})
15+
query.on('row', () => sink.add())
16+
query.on('end', () => sink.add())
17+
})
18+
19+
suite.test('Query with a promise should still support event-listeners', (done) => {
20+
const client = new pg.Client()
21+
const sink = new helper.Sink(3, 1000, () => {
22+
client.end()
23+
done()
24+
})
25+
client.connect()
26+
const query = client.query('SELECT NOW()')
27+
query.on('row', () => sink.add())
28+
query.on('end', () => sink.add())
29+
query.then(() => sink.add())
30+
})

0 commit comments

Comments
 (0)