Skip to content

Commit c3eff0f

Browse files
Ace Nassrifhinkel
andauthored
GCF: refactor connection pooling sample (GoogleCloudPlatform#1714)
* efactor connection pooling sample for Node 8+ * Revert erroneous lint changes Co-authored-by: F. Hinkelmann <franziska.hinkelmann@gmail.com>
1 parent a3f8099 commit c3eff0f

File tree

2 files changed

+15
-26
lines changed

2 files changed

+15
-26
lines changed

functions/tips/index.js

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -74,39 +74,27 @@ exports.lazyGlobals = (req, res) => {
7474
// [END functions_tips_lazy_globals]
7575

7676
// [START functions_tips_connection_pooling]
77+
const axios = require('axios');
78+
7779
const http = require('http');
78-
const agent = new http.Agent({keepAlive: true});
80+
const https = require('https');
81+
82+
const httpAgent = new http.Agent({keepAlive: true});
83+
const httpsAgent = new https.Agent({keepAlive: true});
7984

8085
/**
8186
* HTTP Cloud Function that caches an HTTP agent to pool HTTP connections.
8287
*
8388
* @param {Object} req Cloud Function request context.
8489
* @param {Object} res Cloud Function response context.
8590
*/
86-
exports.connectionPooling = (req, res) => {
87-
req = http.request(
88-
{
89-
host: '',
90-
port: 80,
91-
path: '',
92-
method: 'GET',
93-
agent: agent,
94-
},
95-
(resInner) => {
96-
let rawData = '';
97-
resInner.setEncoding('utf8');
98-
resInner.on('data', (chunk) => {
99-
rawData += chunk;
100-
});
101-
resInner.on('end', () => {
102-
res.status(200).send(`Data: ${rawData}`);
103-
});
104-
}
105-
);
106-
req.on('error', (e) => {
107-
res.status(500).send(`Error: ${e.message}`);
108-
});
109-
req.end();
91+
exports.connectionPooling = async (req, res) => {
92+
try {
93+
const {data} = await axios.get('/', {httpAgent, httpsAgent});
94+
res.status(200).send(`Data: ${data}`);
95+
} catch (err) {
96+
res.status(500).send(`Error: ${err.message}`);
97+
}
11098
};
11199
// [END functions_tips_connection_pooling]
112100

functions/tips/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
"test": "mocha test/*.test.js --timeout=60000 --exit"
1616
},
1717
"dependencies": {
18-
"@google-cloud/pubsub": "^1.0.0"
18+
"@google-cloud/pubsub": "^1.0.0",
19+
"axios": "^0.19.2"
1920
},
2021
"devDependencies": {
2122
"mocha": "^7.0.0",

0 commit comments

Comments
 (0)