Azure интеграция функций с Postgres в Node.js - PullRequest
0 голосов
/ 05 марта 2020

Я хочу получить доступ к Azure Postgres DB из функции Azure. Ниже приведен исходный код node.js для функции Azure.

 module.exports = async function (context, req) {
try {
    context.log('Start function!');
    var pg = require('pg');

    const config = {
        host: 'taxiexample.postgres.database.azure.com',
        user: 'postgres@taxiexample',
        password: 'QscBjk10;',
        database: 'taxi',
        port: 5432,
        ssl: false
    };

    var client = new pg.Client(config);
    const query = 'insert into taxi values (\'2\');';
    context.log(query);
    client.connect();
    var res = client.query(query);
    await client.end();

    context.log(res);

} catch (e) {
    context.log(e);
} finally {
    context.res = {
        status: 200,
        body: "ok"
    };
}

};

Запись не вставляется, объект res возвращает следующую ошибку:

2020-03-04T23:03:59.804 [Information] Promise {
  <rejected> Error: Connection terminated
      at Connection.<anonymous> (D:\home\site\wwwroot\HttpTrigger1\node_modules\pg\lib\client.js:254:9)
      at Object.onceWrapper (events.js:312:28)
      at Connection.emit (events.js:228:7)
      at Socket.<anonymous> (D:\home\site\wwwroot\HttpTrigger1\node_modules\pg\lib\connection.js:78:10)
      at Socket.emit (events.js:223:5)
      at TCP.<anonymous> (net.js:664:12)
}
2020-03-04T23:03:59.811 [Information] Executed 'Functions.HttpTrigger1' (Succeeded, Id=944dfb12-095d-4a28-a41d-555474b2b0ee)

Вы можете мне помочь? Спасибо

1 Ответ

0 голосов
/ 11 марта 2020

Я решил, это была тривиальная ошибка программирования. Ниже приведен правильный исходный код

module.exports = async function (context, req) {

    try {
        context.log('Start function!');
        var pg = require('pg');

        const config = {
            host: 'example.postgres.database.azure.com',
            user: 'postgres@example',
            password: 'passwd;',
            database: 'test',
            port: 5432,
            ssl: true
        };

        var client = new pg.Client(config);
        const query = 'insert into test values (\'2\');';
        context.log(query);

        client.connect(err => {
            if (err) {
                console.error('connection error', err.stack);
            } else {
                console.log('connected');
                client.query(query, (err, res) => {
                    if (err) throw err;
                    console.log(res);
                    client.end();
                })
            }
        });

    } catch (e) {
        context.log(e);
    } finally {
        context.res = {
            status: 200,
            body: "ok"
        };
    }

};
...