LoginSignup
0
1

More than 1 year has passed since last update.

メモ:node.jsでPostgreから簡単なデータをJSONで返す

Posted at

手元で簡単にPostgres+Node.jsでRestAPI的なテストをしたい
という事もあるので自分用のメモ。
DB設計は別でやって、select文を発行してデータを受けたい。ORマッパー等は使わない。
(ORマッピングが嫌い、というのもある。SQLと実行計画は意識するべきだろ派)

環境はWindows
Node.jsとPostgresのインストールは省略。

express

パッケージ管理のnpmを使う前にプロキシ設定が必要な場合は行う

call npm -g config set proxy http://xxx:8080
call npm -g config set https-proxy http://xxx:8080

プロジェクト用のディレクトリを作成し移動。
npm install express
でexpressをインストール。(新しいnpmではsaveオプション不要、らしい)

とりあえずexpressの動作見るだけならこんな感じ

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => res.send('Hello World!'));

postgres

今回はpostgresからデータを検索したいので
npm install pg
でモジュールをインストール

postgresには

create table test(
    'id' integer,
    'name varchar(50)
);

のようにしてテーブル作成後適当にデータを投入してテスト。

検索して、とりあえずJSONで返すだけなら

const express = require('express');
const pgClient = require('pg');
const app = express();
const port = 3000;

var client = new pgClient.Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'postgres',
    password: 'rU9PYNKh',
    port: 5432
});

var pgSelect = {
    text: 'SELECT id,name from test where id=$1',
    values: [0],
}

client.connect()

app.get('/', (req, res) => 
    {
        var reqid = req.query.id;

        pgSelect.values = [reqid];

        client.query(pgSelect)
        .then(result => {return res.json(result.rows[0])} )
        .catch(e => { console.error(e.stack); return res.json({"error":e.stack}); }) // テスト用なのでそのまま返す

    }
);

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

※ アローで省略するやつはスッキリという人もいるが、後から見て分かりづらい気がするのでreturnとかを付けるようにしている

postで登録したい場合はリクエストのボディを取得する必要があるので
npm install body-parser
でインストールしてから利用する。
トランザクションを考えない場合は以下

const express = require('express');
const pgClient = require('pg');
const app = express();
const bodyParser = require('body-parser');
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var client = new pgClient.Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'postgres',
    password: 'password',
    port: 5432
});

var pgSelect = {
    text: 'SELECT id,name from test where id=$1',
    values: [0],
}

var pgInsert = {
    text: 'INSERT INTO test(id,name) VALUES ($1,$2)',
    values: [0,'sample'],
}

client.connect()

app.get('/', (req, res) => 
    {
        var reqid = req.query.id;

        pgSelect.values = [reqid];

        client.query(pgSelect)
        .then(result => {return res.json(result.rows[0]);} )
        .catch(e => { console.error(e.stack); return res.json({"error":e.stack}); }) // テスト用なのでそのまま返す

    }
);

app.post('/', (req, res) =>
    {
        var reqid = req.body.id;
        var reqname = req.body.name;

        pgInsert.values = [reqid,reqname];

        client.query(pgInsert)
        .then(result => {return res.json(result.rows[0]);} )
        .catch(e => { console.error(e.stack); return res.json({"error":e.stack}); }) // テスト用なのでそのまま返す
    }
);

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Chromeの拡張機能のARCでBodyのcontentTypeをapplication/jsonにしてから本文にJSONを書いてPOSTでテスト。

次はもう少し普通に使える環境を。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1