forked from GoogleCloudPlatform/nodejs-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloud-sql.js
More file actions
164 lines (152 loc) · 4.62 KB
/
cloud-sql.js
File metadata and controls
164 lines (152 loc) · 4.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const Knex = require('knex');
const {getCredConfig} = require('./secrets');
const {logger} = require('./logging');
const TABLE = process.env.TABLE || 'pet_votes';
let knex, credConfig;
// Connection pooling config
// See Cloud SQL sample https://github.com/GoogleCloudPlatform/nodejs-docs-samples/tree/master/cloud-sql/postgres/knex
// to learn more about this configuration
const config = {
pool: {
max: 5,
min: 5,
acquireTimeoutMillis: 60000,
},
createTimeoutMillis: 30000,
idleTimeoutMillis: 600000,
createRetryIntervalMillis: 200,
};
// [START cloudrun_user_auth_sql_connect]
// [START run_user_auth_sql_connect]
/**
* Connect to the Cloud SQL instance through UNIX Sockets
*
* @param {object} credConfig The Cloud SQL connection configuration from Secret Manager
* @returns {object} Knex's PostgreSQL client
*/
const connectWithUnixSockets = async credConfig => {
const dbSocketPath = process.env.DB_SOCKET_PATH || '/cloudsql';
// Establish a connection to the database
return Knex({
client: 'pg',
connection: {
user: credConfig.DB_USER, // e.g. 'my-user'
password: credConfig.DB_PASSWORD, // e.g. 'my-user-password'
database: credConfig.DB_NAME, // e.g. 'my-database'
host: `${dbSocketPath}/${credConfig.CLOUD_SQL_CONNECTION_NAME}`,
},
...config,
});
};
// [END run_user_auth_sql_connect]
// [END cloudrun_user_auth_sql_connect]
// Method to connect locally on Windows
const connectWithTcp = credConfig => {
// Extract host and port from socket address
const dbSocketAddr = process.env.DB_HOST.split(':'); // e.g. '127.0.0.1:5432'
// Establish a connection to the database
return Knex({
client: 'pg',
connection: {
user: credConfig.DB_USER, // e.g. 'my-user'
password: credConfig.DB_PASSWORD, // e.g. 'my-user-password'
database: credConfig.DB_NAME, // e.g. 'my-database'
host: dbSocketAddr[0], // e.g. '127.0.0.1'
port: dbSocketAddr[1], // e.g. '5432'
},
...config,
});
};
/**
* Connect to the Cloud SQL instance through TCP or UNIX Sockets
* dependent on DB_HOST env var
*
* @returns {object} Knex's PostgreSQL client
*/
const connect = async () => {
if (!credConfig) credConfig = getCredConfig();
if (process.env.DB_HOST) {
return connectWithTcp(credConfig);
} else {
return connectWithUnixSockets(credConfig);
}
};
/**
* Insert a vote record into the database.
*
* @param {object} vote The vote record to insert.
* @returns {Promise}
*/
const insertVote = async vote => {
if (!knex) knex = await connect();
return knex(TABLE).insert(vote);
};
/**
* Retrieve the latest 5 vote records from the database.
*
* @returns {Promise}
*/
const getVotes = async () => {
if (!knex) knex = await connect();
return knex
.select('candidate', 'time_cast', 'uid')
.from(TABLE)
.orderBy('time_cast', 'desc')
.limit(5);
};
/**
* Retrieve the total count of records for a given candidate
* from the database.
*
* @param {object} candidate The candidate for which to get the total vote count
* @returns {Promise}
*/
const getVoteCount = async candidate => {
if (!knex) knex = await connect();
return knex(TABLE).count('vote_id').where('candidate', candidate);
};
/**
* Create "votes" table in the Cloud SQL database
*/
const createTable = async () => {
if (!knex) knex = await connect();
const exists = await knex.schema.hasTable(TABLE);
if (!exists) {
try {
await knex.schema.createTable(TABLE, table => {
table.bigIncrements('vote_id').notNull();
table.timestamp('time_cast').notNull();
table.specificType('candidate', 'CHAR(6) NOT NULL');
table.specificType('uid', 'VARCHAR(128) NOT NULL');
});
logger.info(`Successfully created ${TABLE} table.`);
} catch (err) {
const message = `Failed to create ${TABLE} table: ${err}`;
logger.error(message);
}
}
};
const closeConnection = () => {
if (!knex) knex.destroy();
logger.info('DB connection closed.');
};
module.exports = {
getVoteCount,
getVotes,
insertVote,
createTable,
closeConnection,
};