Я думаю, проблема в том, что вы не дожидаетесь завершения создания пула.
Кроме того, я предлагаю использовать:
- Обещаниядля ваших функций БД вы почувствуете себя лучше с javascript; D.
- Я предлагаю вам использовать параметризованные функции запросов.Они помогают поддерживать чистоту кода, а также предотвращают необходимость иметь дело с переменными типами / тяжелым экранированием.
- (Кстати, я бы поместил это в другой файл и экспортировал параметризованное обещание через
exports.parameterizedPromise = parameterizedPromise.
Вот пример того, как использовать параметризованное обещание запроса: / *
parameterizedPromise('SELECT * FROM foodtable f WHERE f.flavor = $1 AND f.meal = $2;', ['SPICY', 'BREAKFAST'])
.then(function(result){
console.log(result.rows);
})
.catch(function(error){
console.warn(error);
});
*/
Вот отредактированная версия того, что я использовал некоторое время назад.
const pg = require('pg');
const DBConfig = {
host: 'xxxxxx',
port: 'xxxxxx',
user: 'xxxxxx',
password: 'xxxxxx',
database: 'xxxxxx',
max: 10, // max number of clients in the pool
ssl: true,
idleTimeoutMillis: 30000 // how long a client is allowed to remain idle before being closed
};
const postgresPool = new pg.Pool(DBConfig, function(){
console.log('connected to postgres database');
// Need to wait for the pool to finish connecting before you can fire off your query.
paramaterizedPromise(`CREATE TABLE IF NOT EXISTS favoritememes (id serial PRIMARY KEY, image_url varchar(255), date_favorited TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`, [])
.then(function(result){
console.log(result);
})
.catch(function(error){
console.warn(error);
});
});
postgresPool.on('error', function (err, client) {
// if an error is encountered by a client while it sits idle in the pool
// the pool itself will emit an error event with both the error and
// the client which emitted the original error
// this is a rare occurrence but can happen if there is a network partition
// between your application and the database, the database restarts, etc.
// and so you might want to handle it and at least log it out
console.error('idle client error', err.message, err.stack);
});
const paramaterizedPromise = function(query, params) {
return new Promise( function(resolve, reject){
postgresPool.connect(function(err, client, done) {
if(err) {
reject('Error Fetching Client From Pool', err);
}
client.query(query, params, function(err, result) {
//call `done()` to release the client back to the pool
done(err);
if (err){
reject(err);
} else {
resolve(result);
}
});
});
});
}