pg-promise
を使用していません 。
役立つ場合は、Node.js用のPostgreSQLクライアント
を使用できます。 。 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
ではありません) )ベストプラクティスおよびrequire
としてのdb接続の場合 メインのapp.js
にあります 。
こちらがpg
で モジュール。