The purpose of this tutorial is to setup a database synchronization for your PersistenceJS client-side web application. I use todo example (by Jacob) for this experiment, and the backend is powered by MySQl, NodeJS and persistencejs sync plugin. In short, here are the prequisites:
Stack on the back-end side:
- Nodejs, ExpressJS (NodeJS extension), MySQL & PersistenceJS
- Or use appfog (use for this tutorial's example)
- PersistenceJS, AngularJS
- Or download example from http://jacobmumm.com/demos/todo/ (use for this tutorial)
First, building app.js for NodeJS (server-side scripting)
Declare & Init PersistenceJS (refer to persistencejs example)//persistence declaration
var persistence = require('persistencejs/lib/persistence').persistence;
var persistenceStore = require('persistencejs/lib/persistence.store.mysql');
var persistenceSync = require('persistencejs/lib/persistence.sync.server');
persistenceStore.config(persistence, "localhost", 3306, "todoappdb", "root", "yourpassword");
persistenceSync.config(persistence);
//init sync
var session = persistenceStore.getSession();
var Todo = persistence.define('todo', {
content: 'TEXT',
done: 'BOOL'
});
Todo.enableSync(); //this create table with sync attribute
session.schemaSync(); //generate the table
//nodejs module declaration
var express = require("express");
var app = express();
//init express
app.use(express.static(__dirname));
app.use(express.bodyParser());
app.get('/todoUpdates', function(req, res) {
console.log(" - get /todoUpdates - ");
//var session = persistenceStore.getSession();
session.transaction(function(tx){
persistenceSync.pushUpdates(session, tx, Todo, req.query.since, function(updates) {
res.send(updates);
});
});
});
app.post('/todoUpdates', function(req, res) {
console.log(" - post /todoUpdates - ");
//var session = persistenceStore.getSession();
session.transaction(function(tx){
persistenceSync.receiveUpdates(session, tx, Todo, req.body, function(result) {
res.send(result);
});
});
});
app.listen(3000);
A little change on the client-side, editing services.js from jacob todo example.
Add this line of code after you define your Todo object.
Todo.enableSync('/todoUpdates'); //this will create the table with sync attributes
In the persistence.flush() function, just call the todo.syncall function (to update the back-end).
persistence.flush(function(){
Todo.syncAll(
function(){alert('Your Callback Code');},
function(){alert("Your Sync Complete Code");},
function(){alert("Your Error Handling Code");}
);
});
http://localhost:3002/todo.html
The example of this tutorial can be found here
http://azee01.ap01.aws.af.cm/todo.html
Download link here
https://github.com/anthonyzee/todo-example-sync
No comments:
Post a Comment