【问题标题】:Restful Api express postgres databaseRestful Api express postgres 数据库
【发布时间】:2019-08-31 17:23:45
【问题描述】:

我正在用 node 和 exrpess 开发一个完整的 api,我的数据库是 postgresql,我需要使用 postgres 包 pg-promise。

我知道我需要将我的应用程序与 app.js 文件中的数据库连接起来,但我的问题是,我应该如何在我的端点中使用此连接。

我有路线,我正在使用控制器。

例如

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(路由)

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

products.js(控制器)

    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
    }

如何访问连接以执行类似的操作

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

来自控制器。

更新

好的,我现在正在使用 node-prostgres,pg。我看到更好,感谢人们的建议。

我想创建一次 de db 实例,并在任何地方调用它,特别是在控制器中

我可以使用 app.local 来保存我的客户端吗?连接,进行查询然后关闭它。在任何地方都可以这样做

【问题讨论】:

    标签: node.js postgresql express


    【解决方案1】:

    我没用过pg-promise

    如果有帮助,您可以使用PostgreSQL client for Node.js。你也可以使用async/await

    您可以直接使用 Express 中间件来代替路由器,如下所示。

    //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 
    
    }
    

    对于模块化设计,请使用单独的文件(不是app.js/index.js/server.js)作为数据库连接的最佳实践,并在您的主要app.js 中使用require

    这是help 上的pg 模块。

    【讨论】:

    • 你能解释一下吗please use a separate file (not app.js/index.js/server.js)
    • 使用单独的文件如dbconnector.js来处理与数据库的连接而不是处理连接,主文件中的错误(app.js)。
    【解决方案2】:

    这是一个如何使用它的示例:

    // 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)
      }
    }
    

    旁注:

    来自文档pg-promise

    建立在 node-postgres 之上

    node-postgres 现在也支持 promise。

    【讨论】:

      【解决方案3】:

      你不需要做任何事情,pg-promise 会自动管理连接。它将被分配给查询并在之后立即释放。见examples

      【讨论】:

        猜你喜欢
        • 2020-07-02
        • 1970-01-01
        • 1970-01-01
        • 2014-04-23
        • 2016-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多