|
Persevere client JavaScript actions |
Resulting HTTP communication
|
|
// get the root of the object database
root=pjs.load('root');
|
GET /root
<---
{... root data...}
|
|
root.recipes = []; // create a recipes array, no need to create a
table, just do it with JS! |
PUT /root.recipes
[]
|
|
// query a foods SQL database table (assuming it is plugged into
Jsponic)
oatmeal=pjs.load('foods/[?(@.name="oatmeal")]')[0]; // query using
JSONPath
cookie=pjs.load('foods/[?(@.name="cookie")]')[0];
|
GET foods/[%3F(@.name="oatmeal")]
<---
[{"id":"foods/34",
"name":"oatmeal", "calories":77}] ... |
|
oatmealCookies = {ingredients:[oatmeal,cookie]}; // just mix oatmeal
and cookie, right?
root.recipes.push(oatmealCookies); |
POST /root.recipes
{"ingredients":[{"$ref":"foods/34"},{"$ref":"foods/47"}]}
|
|
recipeApp={calcCalories:function(recipe) {
var cals = 0; recipe.ingredients.forEach( function(ingredient){ cals+=ingredient.calories; });
}
};
recipeApp.calcCalories.runAt="server";
root.recipeApp = recipeApp; //attaching it to a persistent object
will persist it |
PUT /root.recipeApp
{"calcCalories":{"function":"function(recipe){....","runAt":"server"}}
(this is the convention I use to pass
functions so that it stays pure JSON)
|
|
var cookieCalories = recipeApp.calcCalories(oatmealCookies); // this
executes the RPC, the function will be executed on the server (in
Rhino)
cookieCalories --> 290 |
POST /root.recipeApp
{"id":"call1","method":"calcCalories","params":[{"$ref":"/root.recipes[0]"}]}
<---
{"id":"call1","response":290,
"error":null} |
|
// lets load a recipe from a different server, we are now a
mashup!
foreignRecipe =
pjs.load('http://foreignrecipes.com/sushi'); |
<---
{"ingredient":[....]}
|
|
//and stick it in our array/table of recipes
root.recipes.push(foreignRecipe); |
POST /root.recipes
{"$ref":"http://foreignrecipes.com/sushi"}
a get on root.recipes would now
return
[{"ingredients":[{"$ref":"foods/34"},{"$ref":"foods/47"}]},{"$ref":"http://foreignrecipes.com/sushi"}] |
|
I didn't include it in the example, but the PUT and
POST operation return the newly created objects, with their new ids, which can
be used for referencing, which is safer for concurrent DB modifications. If you
download Jsponic, the examples-persisted.html gives a good example of
distributed computing, there is a call to method that searches through customers
on the server. Anyway, that is an overview of my approach to distributed
computing. |