Skip to content

Commit f82f39c

Browse files
authored
Add support to stream factory (#2898)
This changeset enables declaring the `stream` config value as a factory method. Providing a much more flexible control of the socket connection. Defining a custom `stream` config value allows the postgres driver to support a larger variety of environments/setups such as proxy servers and secure socket connections that are used by cloud providers such as GCP. Currently, usage of the `stream` config value is only viable for single connections given that it's only possible to define a single socket stream instance per new Client/Pool instance. By adding support to a factory function, it becomes possible to enable usage of custom socket streams for connection pools. For reference, see the `mysql2` driver for MySQL (linked below) for prior art example of this pattern. Refs: https://github.com/sidorares/node-mysql2/blob/ba15fe25703665e516ab0a23af8d828d1473b8c3/lib/connection.js#L63-L65 Refs: https://cloud.google.com/sql/docs/postgres/connect-overview Signed-off-by: Ruy Adorno <[email protected]> Signed-off-by: Ruy Adorno <[email protected]>
1 parent 3e34816 commit f82f39c

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

packages/pg/lib/connection.js

+5
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,12 @@ class Connection extends EventEmitter {
1414
constructor(config) {
1515
super()
1616
config = config || {}
17+
1718
this.stream = config.stream || new net.Socket()
19+
if (typeof this.stream === 'function') {
20+
this.stream = this.stream(config)
21+
}
22+
1823
this._keepAlive = config.keepAlive
1924
this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis
2025
this.lastBuffer = false

packages/pg/test/unit/connection/startup-tests.js

+12
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,18 @@ test('connection can take existing stream', function () {
77
assert.equal(con.stream, stream)
88
})
99

10+
test('connection can take stream factory method', function () {
11+
var stream = new MemoryStream()
12+
var connectionOpts = {}
13+
var makeStream = function (opts) {
14+
assert.equal(connectionOpts, opts)
15+
return stream
16+
}
17+
connectionOpts.stream = makeStream
18+
var con = new Connection(connectionOpts)
19+
assert.equal(con.stream, stream)
20+
})
21+
1022
test('using any stream', function () {
1123
var makeStream = function () {
1224
var stream = new MemoryStream()

0 commit comments

Comments
 (0)