Neurosync是一个JavaScriptORM库,支持离线和实时操作。没错,是ORM,但并没有疯狂到直接连接到后台数据库。对Neurosync来说,数据库就是后端的RESTAPI,而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(); // truet0.finish( true );t0.done; // truet0.$remove();var t1 = new Todo({name: 'Use Neurosync'});t1.$isSaved(); // falset1.id; // UUIDt1.$save();var t2 = Todo.boot({id: 34, name: 'Profit'}); // Todo data that already exists remotelyt2.$isSaved(); // truet2.name = '???';t2.$hasChanges(); // truevar t3 = Todo.fetch(45); // REST call if doesn't exist locallyTodo.all(); // [t1, t2, t3]Todo.collect(t1, t2); // creates a collection of todosvar allRemote = Todo.fetchAll(function(all) {}); // call REST APIvar f0 = Todo.find('name', 'Download Neurosync'); // first matchvar f1 = Todo.find({done: true});var w0 = Todo.where('done', true); // all done todosvar w1 = Todo.where({finished_at: null});var g0 = Todo.get(34); // get cached versionvar g1 = Todo.grab(34); // get cached version, otherwise call REST APIvar a0 = Todo.grabAll(function(all) {}); // get all cached, if none cached call REST APITodo.ready(function() {}); // when it has been initialized locally and/or remotely (depends on options).Todo.refresh(); // re-fetch from REST APIvar 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();
评论