ポーカー、プログラミング、もぐ

ポーカーとプログラミングともぐもぐについてのブログ。

Node.js + PostgreSQLを使ってアプリケーションを作る(5) データベースを使用する

目次

1, 環境構築

2, Hello World

3, 設定ファイルの追加

4, ルーティング、コントローラーの追加

5, データベースを使用する <-今回

今回やること

RDBMS(今回はPostgreSQL)をインストールし、Node.jsからそれにアクセスして使用できるようにする

手順

# apt-get install postgresql postgresql-contrib
$ /etc/init.d/postgresql start
  • 2, PostgreSQLにユーザーとデータベースを追加
$ sudo su postgres
$ psql

psqlPostgreSQLのターミナル型フロントエンドです。これを使ってアプリケーション用のPostgreSQLユーザー、データベースを作成します。

postgres=# CREATE ROLE nodeuser LOGIN CREATEDB PASSWORD 'nodeuser';
postgres=# CREATE DATABASE nodeuser owner nodeuser;
postgres=# ¥q
$ exit
  • 3, Node.jsにデータベースアクセス用のモジュールを追加 nodeuserにユーザーを切り替え、データベースアクセス用モジュールを追加します。

Expressのドキュメントには、pg-promiseを使用すると書かれているのですが、 クエリ文字列を自分で組み立てなくてはいけないなど辛い部分が多いので、次のモジュールを使用します。

Knex.js - A SQL Query Builder for Javascript

Bookshelf.js

$ npm install --save pg
$ npm install --save knex
$ npm install -g knex // knexはコマンドで使用するのでグローバルインストールする
$ npm install --save bookshelf
  • 4, データベース接続設定を追加
$ knex init

これでknexfile.jsができるので、以下のように記述します。

// Update with your config settings.

module.exports = {

  development: {
    client: 'postgresql',
    connection: {
      database: 'nodeuser',
      user:     'nodeuser',
      password: 'nodeuser'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'migrations'
    }
  },

  production: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  }

};

また、bookshelf.jsを作成し、以下のように記述します。

const config     = require('./config')(process.env.ENV)
const knexconfig = require('./knexfile');
const knex       = require('knex')(knexconfig[config.env]);

const bookshelf = require('bookshelf')(knex);

module.exports = bookshelf;
$ mkdir migrations
$ knex migrate:make create_tasks

これでmigrationsディレクトリ内にマイグレーションファイルが作成されます。 作成されたマイグレーションファイルに、以下のように記述します。

exports.up = function(knex, Promise) {
  return Promise.all([
    knex.schema.createTable('tasks', function(table){
      table.increments('id').primary();
      table.string('title');
      table.string('description');
      table.timestamps();
    })
  ])
};

exports.down = function(knex, Promise) {
  return Promise.all([
    knex.schema.dropTable('tasks')
  ])
};

マイグレーションファイルを作成したら、

$ knex migrate:latest

を実行し、データベースに反映します。 psqlでデータベースの状態を確認すると、テーブルが作成されていることがわかります。

$ psql --username=nodeuser --password --dbname=nodeuser;
nodeuser=> \dt;
              List of relations
 Schema |      Name       | Type  |  Owner
--------+-----------------+-------+----------
 public | migrations      | table | nodeuser
 public | migrations_lock | table | nodeuser
 public | tasks           | table | nodeuser
(3 rows)

ここまでのコードは

github.com

に公開してあります。