Skip to content

Commit fb485ae

Browse files
author
Ace Nassri
authored
Lazily initialize pools + add comments (#735)
1 parent 84e7e7f commit fb485ae

1 file changed

Lines changed: 26 additions & 2 deletions

File tree

functions/sql/index.js

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,18 @@ if (process.env.NODE_ENV === 'production') {
5050
mysqlConfig.socketPath = `/cloudsql/${connectionName}`;
5151
}
5252

53-
const mysqlPool = mysql.createPool(mysqlConfig);
53+
// Connection pools reuse connections between invocations,
54+
// and handle dropped or expired connections automatically.
55+
let mysqlPool;
5456

5557
exports.mysqlDemo = (req, res) => {
58+
// Initialize the pool lazily, in case SQL access isn't needed for this
59+
// GCF instance. Doing so minimizes the number of active SQL connections,
60+
// which helps keep your GCF instances under SQL connection limits.
61+
if (!mysqlPool) {
62+
mysqlPool = mysql.createPool(mysqlConfig);
63+
}
64+
5665
mysqlPool.query('SELECT NOW() AS now', (err, results) => {
5766
if (err) {
5867
console.error(err);
@@ -61,6 +70,9 @@ exports.mysqlDemo = (req, res) => {
6170
res.send(JSON.stringify(results));
6271
}
6372
});
73+
74+
// Close any SQL resources that were declared inside this function.
75+
// Keep any declared in global scope (e.g. mysqlPool) for later reuse.
6476
};
6577
// [END functions_sql_mysql]
6678

@@ -76,9 +88,18 @@ if (process.env.NODE_ENV === 'production') {
7688
pgConfig.socketPath = `/cloudsql/${connectionName}`;
7789
}
7890

79-
const pgPool = new pg.Pool(pgConfig);
91+
// Connection pools reuse connections between invocations,
92+
// and handle dropped or expired connections automatically.
93+
let pgPool;
8094

8195
exports.postgresDemo = (req, res) => {
96+
// Initialize the pool lazily, in case SQL access isn't needed for this
97+
// GCF instance. Doing so minimizes the number of active SQL connections,
98+
// which helps keep your GCF instances under SQL connection limits.
99+
if (!pgPool) {
100+
pgPool = new pg.Pool(pgConfig);
101+
}
102+
82103
pgPool.query('SELECT NOW() as now', (err, results) => {
83104
if (err) {
84105
console.error(err);
@@ -87,5 +108,8 @@ exports.postgresDemo = (req, res) => {
87108
res.send(JSON.stringify(results));
88109
}
89110
});
111+
112+
// Close any SQL resources that were declared inside this function.
113+
// Keep any declared in global scope (e.g. mysqlPool) for later reuse.
90114
};
91115
// [END functions_sql_postgres]

0 commit comments

Comments
 (0)