2015年8月29日 星期六

Sails ORM簡介

Sails ORM

Sails除了API的概念外,他也可以快速地提供Object Relational Model(ORM)的對應,只要透過下面幾個步驟:

說明

Sails的ORM對應是透過幾個部分做設定就可以完成:
  • config/connection.js:設定所要連線的資料庫位置,裡面會有許多的Adaptor的設定,可供後續選用。
  • config/models.js:設定預設的資料庫模組使用哪個Adaptor。
  • api/models/[Object Name].js:透過"sails generate api [Object Name]"所產生的ORM物件,裡面可以再去客製化所擁有的欄位屬性,以結合未來資料輸入的驗證階段使用。

以MySQL資料庫為例

準備

在使用之前,我們先透過下面指令啟動Docker的MySQL服務...(關於Docker部分,可以參考:https://www.gitbook.com/book/peihsinsu/docker-note-book/details)
docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password -d mysql
啟動無誤後,即可在本機使用MySQL服務。(由於一般Mac或Windows是透過boot2docker來啟用docker,所以在連線時候,需要知道Docker Host的位置作為連線使用)。
$ echo $DOCKER_HOST
tcp://192.168.59.103:2376
上面是Docker Host的回覆訊息,其中192.168.59.103即是Docker的連線位置。

Step1: 安裝相關的資料庫模組

在config/connection.js中設定所要連接的MySQL connection位置,設定大致如下:
module.exports.connections = {
  ... (skip)

  /***************************************************************************
  *                                                                          *
  * MySQL is the world's most popular relational database.                   *
  * http://en.wikipedia.org/wiki/MySQL                                       *
  *                                                                          *
  * Run: npm install sails-mysql                                             *
  *                                                                          *
  ***************************************************************************/
  myMysqlServer: {
    adapter: 'sails-mysql',
    host: '192.168.59.103',
    user: 'root',
    password: 'password',
    database: 'mydb'
  },

  ...(skip)

Step2: 設定預設使用的模組

module.exports.models = {
  connection: 'myMysqlServer'
};

Step3: 安裝sails mysql plugin

$ cd $PROJECT_FOLDER
$ npm install sails-mysql --save
sails-mysql@0.11.0 node_modules/sails-mysql
├── waterline-errors@0.10.1
├── async@1.3.0
├── waterline-sequel@0.5.0
├── waterline-cursor@0.0.5 (async@0.9.2, lodash@2.4.2)
├── lodash@3.10.1
└── mysql@2.8.0 (bignumber.js@2.0.7, readable-stream@1.1.13)

Step4: 建立ORM

建立User module

$ sails generate api user
修改user module的欄位
module.exports = {
  adapter: 'myMysqlServer',
  migrate: 'safe',
  id: {
    primaryKey: true,
    type: 'string'
  },
  attributes: {
    name: {
      type: 'string'
    },

    age: {
      type: 'float',
      required: true
    },

    password: {
      type: 'string',
      required: true
    }

  }
}

建立資料庫與對應欄位

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `password` varchar(200) DEFAULT NULL,
  `createdAt` datetime DEFAULT NULL,
  `updatedAt` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

Step5: 啟動並測試

透過Sails的RESTful API定義,要Insert一筆User資料到Sails ORM的對應資料庫中,可以透過下面POST method的方法:
curl -sS http://localhost:1337/user/create -d name=simon -d age=36 -d password=123 -d id=123 -X POST | json
{
  "name": "simon",
  "age": 36,
  "password": "123",
  "id": 123,
  "createdAt": "2015-08-30T05:04:02.291Z",
  "updatedAt": "2015-08-30T05:04:02.291Z"
}
當Inser完,需要檢視資料的狀況,可以透過GET method取回該資料集的內容:
$ curl -sS http://localhost:1337/user | json
[
  {
    "name": "simon",
    "age": 36,
    "password": "123",
    "id": 1,
    "createdAt": "2015-08-30T02:46:54.000Z",
    "updatedAt": "2015-08-30T02:46:54.000Z"
  },
  {
    "name": "simon",
    "age": 36,
    "password": "123",
    "id": 2,
    "createdAt": "2015-08-30T02:47:28.000Z",
    "updatedAt": "2015-08-30T02:47:28.000Z"
  }
]
如果您知道該筆資料的ID,則可以透過下面方式給定:
curl -sS http://localhost:1337/user/123 | json
{
  "name": "simon",
  "age": 36,
  "password": "123",
  "id": 123,
  "createdAt": "2015-08-30T05:04:02.000Z",
  "updatedAt": "2015-08-30T05:04:02.000Z"
}

以CouchDB資料庫為例

Sails抽離了大部份的設定,而ORM connection的設定抽離讓未來切換到其他的資料源可以更方便。下面是從MySQL切換到CouchDB的方式:

Step1: 安裝相關的資料庫模組

在config/connection.js中設定所要連接的CouchDB connection位置,設定大致如下:
module.exports.connections = {
  ... (skip)

  couch: {
    adapter: 'sails-couchdb-orm',
    host: '192.168.59.103',
    port: 5984,
    username: 'admin',
    password: 'adminadmin'
  },

  ...(skip)

Step2: 設定預設使用的模組

module.exports.models = {
  connection: 'couch'
};

Step3: 安裝sails couchdb plugin

$ cd $PROJECT_FOLDER
$ npm install sails-couchdb-orm --save

Step4: 建立ORM

在CouchDB中,由於是屬於NoSQL的性質,我們不需要是先建立資料庫以及對應的Schema。而ORM的設定檔案部分,直接依據上面所設定的部分即可:
module.exports = {
  adapter: 'couch',
  migrate: 'safe',
  id: {
    primaryKey: true,
    type: 'string'
  },
  attributes: {
    name: {
      type: 'string'
    },

    age: {
      type: 'float',
      required: true
    },

    password: {
      type: 'string',
      required: true
    }

  }
}

Step5: 啟動並測試

整體設定完成後,直接依照MySQL部分的啟動測試程序執行,應該就可以在CouchDB中看到對應的資料庫物件與輸入的內容。

其他參考資訊