简体   繁体   中英

Use connection Postgresql on NodeJS (express)

I'm a novice at NodeJS and Express, I followed a tutorial to create a CRUD with a connection to Mysql where "express-myconnection" is used, that connection is recorded as middleware and is used from a model or controller. But I need to work with postgresql, I managed to make the connection, my problem is that I can not call it from a model or a controller

const express = require('express');
const path = require('path');
const morgan = require('morgan');
const app = express();
const { Client } = require('pg');
const connectionData = {
    user: 'postgres',
    host: 'localhost',
    database: 'bex',
    password: 'postgres',
    port: 5432,
}
const client = new Client(connectionData);
client.connect()
client.query('SELECT * FROM bex_usuario')
    .then(response => {
        console.log(response.rows)
        client.end()
    })
    .catch(err => {
        client.end()
    })

How would you create a middleware similar to "express-myconnection", or how would you instantiate from my model or controller without the need to define it in each model or controller?

const { Pool } = require('pg');

function connectionMiddleware(connectionData) {
    const pool = new Pool(connectionData);
    return (req, res, next) => {
        req.pool = pool;
        next();
    }
}

app.use(connectionMiddleware({
    user: 'postgres',
    host: 'localhost',
    database: 'bex',
    password: 'postgres',
    port: 5432,
}));

app.use((req, res, next) => {
    req.pool.connect((err, client, release) => {
        client.query('SELECT NOW()', (err, result) => {
             release();
             if (err) return next(err);
             console.log(result.rows);
             res.send(200);
         });   
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM