Neurosync —— JavaScript 本地離線 ORM 庫

Daisy 8年前發布 | 7K 次閱讀 數據持久化 JavaScript開發 JavaScript

來自: http://www.oschina.net/p/neurosync?fromerr=YrimlQXj

Neurosync 是一個 JavaScript ORM 庫,支持離線和實時操作。沒錯,是 ORM,但并沒有瘋狂到直接連接到后臺數據庫。對 Neurosync 來說,數據庫就是后端的 REST API,而 Neurosync 就是這個 API 的一個門面。

Neurosync 的生命周期非常簡單:

  • 保存數據變更到本地存儲

  • 發起 REST 請求

  • 如果請求成功則刪除本地存儲中的變更數據,標識為已保存,并發布到實時 API

  • 如果請求失敗,因為應用本身是離線的,將等待應用在線并繼續處理數據更改流程

  • 如果有待決的操作但是應用重啟了,數據將會被恢復

一個簡單的 TODO 應用示例代碼:

var Todo = Neuro({
  name: 'todo',
  api: '/api/1.0/todo/',
  fields: ['name', 'finished_at'],
  timestamps: true,
  comparator: ['-finished_at', '-created_at'], // finished go to bottom, most recently created are at the top
  methods: {
    finish: function(finished) {
      this.$save('finished_at', finished ? Date.now() null);
    }
  },
  dynamic: {
    done: function() {
      return !this.finished_at;
    }
  }
});

var t0 = Todo.create({name: 'Download Neurosync'}); t0.$isSaved(); // true t0.finish( true ); t0.done; // true t0.$remove();

var t1 = new Todo({name: 'Use Neurosync'}); t1.$isSaved(); // false t1.id; // UUID t1.$save();

var t2 = Todo.boot({id: 34, name: 'Profit'}); // Todo data that already exists remotely t2.$isSaved(); // true t2.name = '???'; t2.$hasChanges(); // true

var t3 = Todo.fetch(45); // REST call if doesn't exist locally

Todo.all(); // [t1, t2, t3]

Todo.collect(t1, t2); // creates a collection of todos

var allRemote = Todo.fetchAll(function(all) {}); // call REST API

var f0 = Todo.find('name', 'Download Neurosync'); // first match var f1 = Todo.find({done: true});

var w0 = Todo.where('done', true); // all done todos var w1 = Todo.where({finished_at: null});

var g0 = Todo.get(34); // get cached version

var g1 = Todo.grab(34); // get cached version, otherwise call REST API var a0 = Todo.grabAll(function(all) {}); // get all cached, if none cached call REST API

Todo.ready(function() {}); // when it has been initialized locally and/or remotely (depends on options).

Todo.refresh(); // re-fetch from REST API

var search0 = Todo.search({done: true}); // sends a search to the REST API (POST by default)

var searchPaged0 = Todo.searchPaged({done: true, page_offset: 0, page_size: 20}); searchPaged0.$next();</pre> </div>

 本文由用戶 Daisy 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!