<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:series="http://organizeseries.com/"
	>

<channel>
	<title>SitePen Blog &#187; jsonrest</title>
	<atom:link href="http://www.sitepen.com/blog/tag/jsonrest/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sitepen.com/blog</link>
	<description>SitePen Services and notes about Dojo, Persevere, CometD, JavaScript, and the Web</description>
	<lastBuildDate>Wed, 15 May 2013 22:02:34 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5</generator>
		<item>
		<title>Some RPC With Your JsonRestStore</title>
		<link>http://www.sitepen.com/blog/2009/01/29/some-rpc-with-your-jsonreststore/</link>
		<comments>http://www.sitepen.com/blog/2009/01/29/some-rpc-with-your-jsonreststore/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 22:53:45 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[jsonrest]]></category>
		<category><![CDATA[jsonrpc]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[rpc]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/01/29/some-rpc-with-your-jsonreststore/</guid>
		<description><![CDATA[<p>REST is a powerful architecture because of its loose coupling design that facilitates a high level of interoperability. However, even the dissertation that defines REST states that one of the trade-offs of REST is that it &#8220;degrades efficiency, since information is transferred in a standardized form rather than one which is specific to an application&#8217;s [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>REST is a powerful architecture because of its loose coupling design that facilitates a high level of interoperability. However, even the <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5">dissertation that defines REST</a> states that one of the trade-offs of REST is that it &#8220;degrades efficiency, since information is transferred in a standardized form rather than one which is specific to an application&#8217;s needs&#8221;. That is, you might be able to achieve more efficient operation using a mechanism that goes beyond REST&#8217;s uniform interface, that is more specific to your application. This comes at the price of a loss of interoperability and should only be used if necessary, but with this in mind, let&#8217;s look at a good way to use RPCs that integrate with <a href="http://dojotoolkit.org/">Dojo</a>&#8216;s REST module, the <a href="http://docs.dojocampus.org/dojox/data/JsonRestStore">JsonRestStore</a>. This approach builds on the REST architecture, while allowing exceptions as needed.</p>
<p><span id="more-602"></span></p>
<p>With this method, we will use JSON-RPC to send RPC requests to a server. The JSON-RPC calls are integrated with our REST architecture by using the URL of the target resource/object as the URL for the JSON-RPC request. Let&#8217;s send a request to send an email to one of our friends. A targeted JSON-RPC call might look like:</p>
<pre lang="javascript">
POST /Friend/dylan

{"method": "sendEmail",
 "params": ["Hi there"],
 "id":"call0"
}
</pre>
<p>One of the advantages of this approach is that it allows for a very object-oriented approach to RPC. JSON-RPC by itself only provides a flat procedural calling mechanism, but by targeting the calls to resource-associated URLs, the RPCs have a target object and can trigger a true object-oriented method call.</p>
<h2>Inheritance in JsonRestStore</h2>
<p>Now, let&#8217;s look at how we can set up a JsonRestStore so we can easily make RPC requests through methods. First, the JsonRestStore allows you to add functions on a prototype object that will be inherited by all items in the store. The prototype object is defined by the schema object that can be passed to the JsonRestStore on construction. For example, we could define a function that would calculate the full name of a person:</p>
<pre lang="javascript">
var friendSchema = {
	prototype: {
		getFullName: function(){
			return this.firstName + ' ' + this.lastName;
		}
	}
}
var friendStore = new dojox.data.JsonRestStore(
	{target:"/Friend/", schema: friendSchema});
</pre>
<p>And now this function will be inherited by the items in our friendStore:</p>
<pre lang="javascript">
var newFriend = friendStore.newItem({firstName: "Abraham", lastName: "Lincoln"});
newFriend.getFullName() -> "Abraham Lincoln"
</pre>
<p>This functionality is covered in more detail in our post about the <a href="http://www.sitepen.com/blog/2008/11/21/effective-use-of-jsonreststore-referencing-lazy-loading-and-more/">effective use of JsonRestStore</a>.</p>
<p>Now, we will create a function that can add a function that triggers the JSON-RPC request when called (understanding the internals of this function is not critical, you may want to simply copy it):</p>
<pre lang="javascript">
function addRpcFunction(schema, name){
	schema.prototype[name] = function(){
		// execute a JSON-RPC call
		var deferred = dojo.rawXhrPost({
			url: store.target + store.getIdentity(this),
			// the JSON-RPC call
			postData: dojo.toJson({
				method: name,
				id: callId++,
				params: dojo._toArray(arguments)
			}),
			handleAs: "json"
		});
		deferred.addCallback(function(response){
			// handle the response
			return response.error ?
				new Error(response.error) :
				response.result;
		});
		return deferred;
	};

}
var callId = 0;
</pre>
<p>Now we can easily add our sendEmail function to the prototype of the schema, as well as any other methods we want:</p>
<pre lang="javascript">
addRpcFunction(friendSchema, "sendEmail");
addRpcFunction(friendSchema, "poke");
</pre>
<p>Triggering an RPC is now as simple as a method call on an item from the store:</p>
<pre lang="javascript">
friendStore.fetchItemByIdentity({
	identity: "dylan",
	onItem: function(item){
		item.sendEmail("Hi there");
	}
});
</pre>
<p>And this will trigger the HTTP request containing the JSON-RPC call we described at the beginning of the article:</p>
<pre lang="javascript">
POST /Friend/dylan

{"method": "sendEmail",
 "params": ["Hi there"],
 "id":"call0"
}
</pre>
<p>The server can then easily find the associated resource and call the server-side <code>sendEmail</code> method with the resource as the target. The server could then respond with:</p>
<pre lang="javascript">
POST /Friend/dylan

{"result": true,
 "error": null,
 "id":"call0"
}
</pre>
<p>The client method call will return a <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/miscellaneous/communication-between-threads-do">Deferred</a> object. This object can be used to get the return value from the RPC call when it finishes (it will execute asynchronously):</p>
<pre lang="javascript">
item.sendEmail("Hi there").addCallback(function(result){
	// with the server response above, the result value will be true
});
</pre>
<p>All of this is done with an intuitive combination of REST and RPC, using the widely adopted JSON-RPC format. <a href="http://www.persvr.org/">Persevere</a> is one server that supports this approach, allowing JavaScript functions on the server to be executed via JSON-RPC requests with persisted objects as the targets. However, it is straightforward to implement this mechanism yourself, as the JSON-RPC specification is very simple.</p>
<h2>Summary</h2>
<p>Adhering to a uniform interface as prescribed by REST and defined by the HTTP specification will certainly afford maximum interoperability. However, if your application needs to use specific functions for maximum efficiency, or for operations that don&#8217;t fit well with REST (sending an email is a good example, since it is awkward to model as a state change), JSON-RPC is a great tool for sending specific RPC using a format with a high degree of adoption. Using targeted JSON-RPC allows RPCs to build on the REST architecture and work in conjunction with it. This combination provides an object-oriented technique for remote calls. Many of the benefits of REST can realized, while the freedom to perform more customized operations is still available.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/01/29/some-rpc-with-your-jsonreststore/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Effortless Offline with OfflineRest</title>
		<link>http://www.sitepen.com/blog/2008/09/23/effortless-offline-with-offlinerest/</link>
		<comments>http://www.sitepen.com/blog/2008/09/23/effortless-offline-with-offlinerest/#comments</comments>
		<pubDate>Tue, 23 Sep 2008 07:01:18 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Dojo Grid]]></category>
		<category><![CDATA[Dojo Offline]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jsonrest]]></category>
		<category><![CDATA[offline]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2008/09/23/effortless-offline-with-offlinerest/</guid>
		<description><![CDATA[<p>There is growing support in browsers for offline capabilities with the HTML 5 specification for local storage, offline notifications, and offline application cache, but adapting an application to store changes locally and do synchronization when connectivity is restored remains a major challenge for developers. Dojo 1.2&#8242;s new dojox.rpc.OfflineRest module automates the local storage of data [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2008/09/offlinerest.png' style='float:right' alt='offlinerest.png' />  There is growing support in browsers for offline capabilities with the HTML 5 specification for local storage, offline notifications, and offline application cache, but adapting an application to store changes locally and do synchronization when connectivity is restored remains a major challenge for developers. Dojo 1.2&#8242;s new dojox.rpc.OfflineRest module automates the local storage of data and synchronization by leveraging the Dojo Data and REST abstractions. The OfflineRest module augments the JsonRest service in Dojo such that requests are cached in local storage for offline access, and modification requests (put, post, and delete) modify the cache and are recorded for delivery to the server; immediately if online, otherwise when connectivity is restored. Furthermore, JsonRest is the core engine used by <a href="http://www.sitepen.com/blog/2008/06/13/restful-json-dojo-data/">JsonRestStore</a>.  Consequently, you can simply use the standard Dojo Data API with the JsonRestStore and effortlessly add offline capability with no modifications to your data interaction code. The underlying Rest service automates the handling of caching, storing data locally, and syncing changes. In addition the new OfflineRest module has no dependency on plugins, but rather progressively utilizes offline features that are available, while still operating properly on legacy browsers without offline support.
</p>
<p><span id="more-412"></span></p>
<p>Our <a href="http://persevere.sitepen.com/examples/trails.html">demonstration of OfflineRest is a simple database of hiking trails</a>. Here in Salt Lake City, we have a <a href="http://www.utahmountainbiking.com/trails/idx-slc.htm">vast array of trails</a> close to my house. However, despite their proximity to the city, most trails still lack internet access. Our &#8220;<a href="http://persevere.sitepen.com/examples/trails.html">Database for the Outdoors</a>&#8221; can be used on the trail, offline, with the ability to view, add, update, and delete trails. Currently it can run on Firefox 3, but as other browsers with HTML 5 offline capabilities are released, they should work as well. This application is simply built by interacting with the <a href="http://www.sitepen.com/blog/2008/06/13/restful-json-dojo-data/">JsonRestStore module</a>, using the standard Dojo Data API. Dojo automatically stores all data changes in local storage, and if or when connectivity becomes available, the data changes are persisted to the server using the Rest service. By building the application on top of the Dojo Data API, the OfflineRest module allows us to easily add offline capabilities. Dojo then handles synchronization and offline access to data, which is usually the complex part of adding offline capabilities to an application.</p>
<p>To enable offline support with OfflineRest, load the OfflineRest module prior to loading the data store:</p>
<pre lang="javascript">
dojo.require("dojox.rpc.OfflineRest");
dojo.require("dojox.data.JsonRestStore");
</pre>
<p>With OfflineRest loaded, you can now add stores to the OfflineRest module for offline support. First, initialize your data store, and then call the addStore method on OfflineRest:</p>
<pre lang="javascript">
trailStore = new dojox.data.JsonRestStore({url:"/Trail"});
dojox.rpc.OfflineRest.addStore(trailStore,"");
</pre>
<p>Now the trailStore will have offline support. Any data modifications that are made through the trailStore will be persisted in local storage and synchronized to the server when connectivity is available. Data modifications can be done with the standard Dojo Data API, for example:</p>
<pre lang="javascript">
var item = trailStore.newItem();
trailStore.setValue(item,"foo","bar");
</pre>
<p>OfflineRest handles the synchronization of sending all data modifications to the server. However, the current version of OfflineRest does not re-query the server for any data that it has cached locally. Consequently, it may be desirable to force a download of data from the server based on data that may have changed on the server while offline. Such an action can be performed and triggered by connecting to the <code>downloadChanges()</code> method on OfflineRest:</p>
<pre lang="javascript">
dojo.connect(dojox.rpc.OfflineRest, "downloadChanges", function(){
	.. download changes or refresh the page ..
});
</pre>
<p>Without defining the offline caching of the resources, this application will be available offline as long as the resources in the application are still in the browser cache, but this is not guaranteed. In order to ensure that your application is always available offline, the new HTML 5 offline cache manifest can be used to ensure that all the resources will be available so your application can always load even when offline and the application hasn&#8217;t been accessed for a while. Firefox 3 has implemented support for offline resources, and has <a href="http://developer.mozilla.org/en/Offline_resources_in_Firefox">detailed instructions on how to build a manifest</a> to ensure your resources are included. Our trails application includes a manifest to leverage this support when available:</p>
<pre lang="bash">
CACHE MANIFEST
# v1

http://localhost/example/trails.html


http://localhost/jsclient/dojo/dojo.js


http://localhost/jsclient/dojox/grid/resources/Grid.css


http://localhost/jsclient/dojo/resources/dojo.css


http://localhost/jsclient/dojo/resources/dojo.css


http://localhost/dojox/data/PersevereStore.js


http://localhost/dojox/grid/DataGrid.js


http://localhost/dojox/rpc/OfflineRest.js

</pre>
<p>And we reference the manifest from our HTML page:</p>
<pre lang="html4strict">
<html manifest="http://localhost/examples/cache-manifest">
</pre>
<p>This offline demo application was built with <a href="http://sitepen.com/labs/persevere.php">Persevere</a>, and this demo is included with the <a href="http://code.google.com/p/persevere-framework/">Persevere download</a> if you want to try it out yourself.</p>
<p>With OfflineRest, synchronization is encapsulated and handled by Dojo with data modifications persisted locally or remotely as connectivity allows. For developers that utilize JsonRestStore, offline support can be a relatively easy addition to your application. OfflineRest can also utilize the offline features in current and coming browsers like Firefox 3.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2008/09/23/effortless-offline-with-offlinerest/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
