2017-06-20 73 views
0

我正在使用nodejs作爲我的REST api主機。整體功能非常基礎。也就是說,做一個REST調用,它應該執行postgres數據庫查詢並返回數據。我遇到的問題是整個代碼組織。使用postgres和nodejs連接池

我有server.js有基本的初始化。現在,我應該在哪裏放置postgres連接,並在需要時調用它來查詢db。目前的結構如下。所以我認爲我應該將postgres連接代碼移動到server.js?什麼應該是正確的結構

server.js

"use strict"; 

var express = require('express'), 
    app = express(), 
    port = process.env.PORT || 4001, 
    bodyParser = require('body-parser'); 

    app.use(bodyParser.urlencoded({ extended: true })); 
    app.use(bodyParser.json()); 
    app.use(function (req, res, next) { 

    // Website you wish to allow to connect 
    res.setHeader('Access-Control-Allow-Origin', '*') 
    // Request methods you wish to allow 
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); 
    // Request headers you wish to allow 
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); 
    // Set to true if you need the website to include cookies in the requests sent 
    // to the API (e.g. in case you use sessions) 
    res.setHeader('Access-Control-Allow-Credentials', true); 
    // Pass to next layer of middleware 
    next(); 
}); 
var routes = require('./api/routes/pushRoutes'); 
routes(app); 

app.listen(port); 
console.log('push notification server started on: ' + port); 

pushController.js

'use strict'; 

exports.send_notification = function(req, res) { 
    console.log("start of send_notification "); 

    if (req.method == 'POST') { 
     var jsonString = ''; 

     req.on('data', function (data) { 
      jsonString += data; 
     }); 

     req.on('end', function() { 
      console.log(JSON.parse(jsonString)); 
      var json = JSON.parse(jsonString); 
      var timeNow = json.message; 

      //get device token from db 
      var deviceToken = ''; 
      var pg = require('pg') 
      var format = require('pg-format') 
      var PGUSER = 'deploy' 
      var PGDATABASE = 'oscpushserver' 
      var config = { 
       user: PGUSER, // name of the user account 
       database: PGDATABASE, // name of the database 
       max: 10, // max number of clients in the pool 
       idleTimeoutMillis: 30000 
      } 

      var pool = new pg.Pool(config) 
      var myClient 

      pool.connect(function (err, client, done) { 
       if (err) console.log(err) 
       app.listen(3000, function() { 
       console.log('listening on 3000') 
       }) 
       myClient = client 
       var ageQuery = format('SELECT * from push_table WHERE seq_id = 1') 
       myClient.query(ageQuery, function (err, result) { 
       if (err) { 
        console.log(err) 
       } 
       console.log("row data:" + result.rows[0]) 
       console.log("device id from db:" + result.rows[0].device_id) 
       deviceToken =result.rows[0].device_id; 


       }) 
      }); 


      res.json(JSON.parse(jsonString)); 
     }); 
    } 

}; 
+0

看起來是正確的,如果你想要更短的代碼,你可能想嘗試https://node-postgres.com/ –

+0

以及pool.connect內的應用程序沒有解決我的情況,因爲它是在server.js – Vik

+0

哦等待我的壞你已經使用node-postgres。我可以問你爲什麼把應用程序放入池中。你已經有應用程序監聽server.js –

回答

1

我假設你想使一個REST API,只是從數據庫獲取數據。

server.js

看起來大部分地區細,除了你沒有正確使用的路由。要使用已定義的路由使用app.use:

app.use('/', routes); 

database.js 我會創造另一個文件,你可以把數據庫憑據在一個地方,並創建一個新池。

var pg = require('pg') 
var PGUSER = 'deploy' 
var PGDATABASE = 'oscpushserver' 
var config = { 
    user: PGUSER, // name of the user account 
    database: PGDATABASE, // name of the database 
    max: 10, // max number of clients in the pool 
    idleTimeoutMillis: 30000 
} 

var pool = new pg.Pool(config); 

module.exports = pool; 

pushController

我假設你想要求在server.js文件。所以請確保路徑指向'.../pushController'而不是'./api/routes/pushRoutes'。

const express = require('express'); 
const router = express.Router(); 
const format = require('pg-format'); 
const pool = require('../path/to/database.js'); 

router.get(function(req, res, next) { 
    pool.connect(function (err, client, done) { 
    if (err) throw new Error(err); 
    var ageQuery = format('SELECT * from push_table WHERE seq_id = 1') 
    client.query(ageQuery, function (err, result) { 
     if (err) throw new Error(err); 
     res.json(result.rows[0]); 
    }) 
    }); 
}); 

module.exports = router; 

所以,現在,您的API服務器的GET請求應該從您的postgres數據庫返回一個json對象。

有許多關於如何使用node和postgres製作REST API的示例。其中之一是:https://github.com/mjhea0/node-postgres-todo