2012年6月5日 星期二

Apache官方支援的Node.js API for CouchDB

Apache官方支援的Node.js API for CouchDB : cradle
下面是實作範例
Shcema設計:
  • key的部分固定使用uuid + @ + name:
  • 另外一個附屬欄位description作為文件描述

實作:
var util = require('util');
var cradle = require('cradle');

//連線資訊設定
var port = 5984;
var options = {
  cache : true,
  raw : false,
  auth: { username: 'username', password: 'password' }
};

//開啟DB
var db = new(cradle.Connection)(url, port, options).database('snapshot_logger');

/**
  * 取得document
  */
exports.getSnapshotDescript = function(uuid, name, callback){
  var snapname = util.format('%s@%s',uuid, name);
  db.get(snapname, function (err, doc) {
    var result = {}
    if(err){
      result.msg = 'error';
      result.error = err;
    }else {
      result.msg = 'success';
      result.doc = doc;
    }

    callback(result);
  });
};

/**
 * 儲存或更新一筆資料
 */
exports.saveSnapshotDescript = function(uuid, name, descript, callback) {
  var snapname = util.format('%s@%s',uuid, name);
  var data =
    {
      snapname: snapname,
      uuid: uuid,
      descript: descript
    };

  var result = {};
  db.save(snapname,
    data,
    function (err, res) {
      if (err) {
        result.msg = 'error';
        result.err = err;
      } else {
        result.msg = 'success';
        result.doc = res;
      }
      callback(result);
  });
};

/* 刪除一筆資料 */
exports.delSnapshotDescript = function(uuid, name, callback) {
  var snapname = util.format('%s@%s',uuid, name);
  var result = {};
  this.getSnapshotDescript(uuid, name, function(result){
    if(result.doc) {
      db.remove(snapname, function (err, res) {
        console.log(res);
      });
    } else {
      result.msg = 'warning';
      result.log = util.format('[Warning]Doc not found of _id:%s',snapname);
    }
    callback(result);
  });
}



使用方式:
/* Save or update document */
this.saveSnapshotDescript(uuid,name,'TEST 1234', function(result){
  console.log('Something done...');
  console.log('Save result.... %s', JSON.stringify(result));
}); 

/* Delete Document */
this.delSnapshotDescript(uuid,name, function(result){
  console.log( JSON.stringify(result));
}); 

/* Get Document */
this.getSnapshotDescript(uuid, name, function(res) {
  console.log('Get result:' + JSON.stringify(res));
});