Restful Api express postgres database

倾然丶 夕夏残阳落幕 提交于 2020-01-16 01:20:33

问题


I´m developing a rest full api with node and exrpess, my database is postgresql, I need to use the postgres package pg-promise.

I know that I need to connect my app with the database in the app.js file, but my question is, How I should use this connection in my endpoints.

I have routes and I am using controllers.

For example

app.js

//in this file, suppously I have to to the connection 
const db = pgp('postgres://john:pass123@localhost:5432/products');

app.use('/products', productsRoute);

products.js (route)

 router.get('/', ProductsController.get_all_products);

products.js (controller)

    exports.get_all_products = (req, res, next ) => {
        // Here i want to use de database connection to do the query to find all
        //products in the database
    }

How do I get access to the connection to do something like

db.any('SELECT * FROM products WHERE active = $1', [true])
    .then(function(data) {
        // success;
    })
    .catch(function(error) {
        // error;
    });

From the controller.

Update

Ok, I´m using now node-prostgres, pg. I saw is better, Thanks for the advice people.

I want to create one time de db instance, and call it anywhere, in specific in the controllers

Could I use app.local to save my client?, connect, do a query and then close it. Do this anywhere


回答1:


I haven't used pg-promise.

If it helps, you can use PostgreSQL client for Node.js. You can also use async/await with it.

Instead of a router, you can use Express middle-ware straightaway as follows.

//app.js:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 1234

const db = require('./dbconnector')

//...omitted for brevity`
// 'db' is exported from a file such as 
// dbconnector.js.
app.get('/products', db.getProducts) 


//In dbconnector.js:
const Pool = require('pg').Pool
const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'mydb',
  password: 'mypwd',
  port: 5432,
})

const getProducts = (request, response) => {
    pool.query('SELECT * FROM products ORDER BY id 
ASC', (error, results) => {
      if (error) {
        throw error
      }
      response.status(200).json(results.rows)
    })
  }

// ...omitted for brevity

module.exports = {
 getProducts 

}

For modular design, please use a separate file (not app.js/index.js/server.js) for db connections as best practice and require that in your main app.js.

Here is help on pg module.




回答2:


Here's an example how to use it:

// mydb.js
async function someDbQuery() {
  let result;
  try {
    result = db.any('SELECT * FROM products WHERE active = $1', [true])
  } catch (e) {
    throw e
  }
  return result;
}
module.exports = someDbQuery;

// in your controller after importing
const { someDbQuery } = require('./mydb.js')
exports.get_all_products = async (req, res, next ) => {
  // Here i want to use de database connection to do the query to find all
  //products in the database
  try {
    const result = await someDbQuery();
    // use result here
  } catch (e) {
    // handle error
    console.error(e)
  }
}

Side note:

From the docs pg-promise

Built on top of node-postgres

node-postgres now supports promise too.




回答3:


You do not need to do anything, pg-promise manages connections automatically. It will be allocated for the query and released right after. See examples.



来源:https://stackoverflow.com/questions/55609376/restful-api-express-postgres-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!