我正在使用Node.js作为我的REST API主机。总体功能非常基本,即进行REST调用,应查询PostgreSQL数据库并返回数据。我遇到的问题是代码组织方面存在问题。
我有一个server.js文件,其中包含基本初始化过程。现在,我应该把PostgreSQL连接放在哪里,并在需要时调用它来查询数据库。当前的结构如下所示。因此,我认为我应该将PostgreSQL连接代码移动到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));
});
}
};