Skip to content

Commit

Permalink
GCF: refactor connection pooling sample (#1714)
Browse files Browse the repository at this point in the history
* efactor connection pooling sample for Node 8+

* Revert erroneous lint changes

Co-authored-by: F. Hinkelmann <franziska.hinkelmann@gmail.com>
  • Loading branch information
Ace Nassri and fhinkel authored Apr 10, 2020
1 parent a3f8099 commit c3eff0f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 26 deletions.
38 changes: 13 additions & 25 deletions functions/tips/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,39 +74,27 @@ exports.lazyGlobals = (req, res) => {
// [END functions_tips_lazy_globals]

// [START functions_tips_connection_pooling]
const axios = require('axios');

const http = require('http');
const agent = new http.Agent({keepAlive: true});
const https = require('https');

const httpAgent = new http.Agent({keepAlive: true});
const httpsAgent = new https.Agent({keepAlive: true});

/**
* HTTP Cloud Function that caches an HTTP agent to pool HTTP connections.
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
exports.connectionPooling = (req, res) => {
req = http.request(
{
host: '',
port: 80,
path: '',
method: 'GET',
agent: agent,
},
(resInner) => {
let rawData = '';
resInner.setEncoding('utf8');
resInner.on('data', (chunk) => {
rawData += chunk;
});
resInner.on('end', () => {
res.status(200).send(`Data: ${rawData}`);
});
}
);
req.on('error', (e) => {
res.status(500).send(`Error: ${e.message}`);
});
req.end();
exports.connectionPooling = async (req, res) => {
try {
const {data} = await axios.get('/', {httpAgent, httpsAgent});
res.status(200).send(`Data: ${data}`);
} catch (err) {
res.status(500).send(`Error: ${err.message}`);
}
};
// [END functions_tips_connection_pooling]

Expand Down
3 changes: 2 additions & 1 deletion functions/tips/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"test": "mocha test/*.test.js --timeout=60000 --exit"
},
"dependencies": {
"@google-cloud/pubsub": "^1.0.0"
"@google-cloud/pubsub": "^1.0.0",
"axios": "^0.19.2"
},
"devDependencies": {
"mocha": "^7.0.0",
Expand Down

0 comments on commit c3eff0f

Please sign in to comment.