Node.js + PostgreSQLを使ってアプリケーションを作る(6) ORMを利用する
目次
6, ORMを利用する <-今回
今回やること
Bookshelf.js (ORM)を利用して、データを表示する
手順
- 1, テスト用のデータをpsqlを利用して登録する
$ psql --username=nodeuser --password --dbname=nodeuser nodeuser=> INSERT INTO tasks(title, description, created_at, updated_at) VALUES('test', 'test task', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP); nodeuser=> ¥q
- 2, モデルを作成する modelsディレクトリを作成し、そこにTaskモデルを追加します。
$ mkdir models $ vim models/task.js
models/task.jsには以下のように記述します。
'use strict'; const Bookshelf = require('../bookshelf'); const Promise = require('bluebird'); const Task = Bookshelf.Model.extend({ tableName: 'tasks' }, { }); module.exports = Task;
- 3, コレクションを作成する collectionsディレクトリを作成し、そこにTaskコレクションを作成します。
$ mkdir collections $ vim collections/taskCollection.js
collections/taskCollection.jsには以下のように記述します。
const Bookshelf = require('../bookshelf'); const Task = require('../models/task'); const Promise = require('bluebird'); const TaskCollection = Bookshelf.Collection.extend({ model: Task, }, { getList: function(){ return new this() .fetch() .then (function (collection){ return collection.toJSON(); }) .catch (function (error){ throw error ; }); } }); module.exports = TaskCollection;
- 4, コレクションを利用する controllers/public/index.jsを以下のように書き換えます。
'use strict'; const Promise = require('bluebird'); const TaskCollection = require('../../collections/taskCollection'); const getIndex = function(req, res) { TaskCollection.getList() .then(function (tasks) { res.json(tasks); }) .catch (function (error) { res.status(500).json({msg: error.message}); }); }; module.exports = { getIndex: getIndex };
この状態でhttp://localhost:3000にアクセスすると、以下のようにtasksの内容が表示されます
[{"id":1,"title":"test","description":"test task","created_at":"2017-01-15T09:32:10.123Z","updated_at":"2017-01-15T09:32:10.123Z"}]
ここまでのコードは
こちらに公開してあります。