Created
April 22, 2013 14:49
-
-
Save jalalhejazi/5435657 to your computer and use it in GitHub Desktop.
nodejs: JSON Cache bidirectional GET and POST data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
JSON Cache Example with node.js | |
This is an example, not a useful library. | |
It demostrates bi-directional JSON transport to a simple service capable of caching arbitrary JSON objects by id. To run the example, type: | |
$ node server.js | |
"Browse to http://127.0.0.1:8181/client.htm to see the client test page" | |
That will start the server running. It will tell you a URL of a test page that uses jQuery to consume the service. | |
You can then use the put() and get() | |
calls to cache JSON objects. | |
Objects persist only in memory in the server process, and are lost when the server stops. | |
From my point of view, the interesting part is the transport: | |
1) Serializing | |
2) Deserializing, | |
3) GETing, | |
4) POSTing with correct MIME types | |
5) Basic error handling, both server-to-client and client-to-server. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<title>JSON Bidirectional GET POST data</title> | |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> | |
<script type="text/javascript"> | |
function put(id, data, callback) { | |
$.ajax('http://127.0.0.1:8181/' + id + '/', { | |
type: 'POST', | |
data: JSON.stringify(data), | |
contentType: 'text/json', | |
success: function() { if ( callback ) callback(true); }, | |
error : function() { if ( callback ) callback(false); } | |
}); | |
} | |
function get(id, callback) { | |
$.ajax('http://127.0.0.1:8181/' + id + '/', { | |
type: 'GET', | |
dataType: 'json', | |
success: function(data) { if ( callback ) callback(data); }, | |
error : function() { if ( callback ) callback(null); } | |
}); | |
} | |
// run a simple put/get test | |
put('echo1', { x: 42, items: ['echo', 'echo'], label: 'echo...echo...', note: "This object was created on the client, sent to the server, and later retrieved, using JSON transport for both trips." }, function(success) { | |
if ( success ) { | |
get('echo1', function(data) { | |
$('#echo').html(JSON.stringify(data)); | |
}); | |
} else { | |
alert('put failed!'); | |
} | |
}); | |
// test forms. | |
$(function() { | |
$('#get-form').submit(function(e) { | |
e.preventDefault(); | |
var id = $('#get-id-field').val(); | |
get(id, function(data) { | |
if ( console ) console.log(data); | |
$('#echo').html(JSON.stringify(data)); | |
}); | |
}); | |
$('#put-form').submit(function(e) { | |
e.preventDefault(); | |
var id = $('#put-id-field').val(); | |
try { | |
var value = JSON.parse($('#put-value-field').val()); | |
} catch (e) { | |
alert('please use valid JSON in the value box.'); | |
return; | |
} | |
put(id, value, function(success) { | |
if ( success ) { | |
alert('success!'); | |
$('#get-id-field').val(id); | |
} else { | |
alert('error!'); | |
} | |
}); | |
}); | |
}); | |
</script> | |
<style> | |
.box { | |
border: 1px dotted blue; padding: 10px; margin: 10px; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="timestamp" class="box"> | |
Timestamp: <script>document.write(new Date());</script> | |
</div> | |
<div id="echo" class="box"> | |
</div> | |
<div id="get" class="box"> | |
Get | |
<form id="get-form" method="POST"> | |
ID:<input name="id" id="get-id-field" value="quote1"><br> | |
<button id="get-button" type="submit">Get</button> | |
</form> | |
</div> | |
<div id="put" class="box"> | |
Put | |
<form id="put-form" method="POST"> | |
ID:<input name="id" id="put-id-field" value="jalal"><br> | |
<p> | |
JSON Value: | |
</p> | |
<textarea name="value" id="put-value-field" rows="2" cols="100">{ "name": "Jalal", "says": "Experience is simply the name we give our mistakes" } | |
</textarea> | |
<br> | |
<button id="put-button" type="submit">Put json_data</button> | |
</form> | |
</div> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var url = require('url'); | |
// just start with a few random things defined for testing. | |
var store = { | |
secret: 'hey! this was supposed to be a secret!', | |
quote1: { | |
quote: "Walking on water and developing software from a specification are easy if both are frozen.", | |
author: "Edward V Berard" | |
}, | |
quote2: { | |
quote: "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.", | |
author: "Brian Kernighan" | |
}, | |
quote3: { | |
quote: "Measuring programming progress by lines of code is like measuring aircraft building progress by weight.", | |
author: "Bill Gates" | |
} | |
}; | |
var server = http.createServer(function(request, response) { | |
try { | |
var id = url.parse(request.url).pathname; | |
if (id.charAt(0) === '/') id = id.slice(1); | |
if (id.charAt(id.length - 1) === '/') id = id.slice(0, id.length - 1); | |
// as a special case, server client.html as a static HTML page. | |
if (id === 'client.html') { | |
var fs = require('fs'); | |
fs.readFile('client.htm', function(error, data) { | |
response.writeHead(200, { | |
'content-type': 'text/html' | |
}); | |
response.end(data); | |
}); | |
} else { | |
if (request.method === 'POST') { | |
// the body of the POST is JSON payload. It is raw, not multipart encoded. | |
var data = ''; | |
request.addListener('data', function(chunk) { | |
data += chunk; | |
}); | |
request.addListener('end', function() { | |
store[id] = JSON.parse(data); | |
response.writeHead(200, { | |
'content-type': 'text/plain' | |
}); | |
response.end(); | |
}); | |
} else if (request.method === 'GET') { | |
// exact id lookup. | |
if (id in store) { | |
response.writeHead(200, { | |
'content-type': 'text/json' | |
}); | |
response.write(JSON.stringify(store[id])); | |
response.end('\n'); | |
} else { | |
response.writeHead(404, { | |
'content-type': 'text/plain' | |
}); | |
response.write('no data with this request > ' + id); | |
response.end('\n'); | |
} | |
} else { | |
response.writeHead(404); | |
response.end('bad method'); | |
} | |
} | |
} catch (e) { | |
response.writeHead(500, { | |
'content-type': 'text/plain' | |
}); | |
response.write('ERROR:' + e); | |
response.end('\n'); | |
} | |
}); | |
server.listen(8181); | |
console.log("*********************************************************************** \n"); | |
console.log("Go to http://127.0.0.1:8181/client.htm to see the client test page. \n "); | |
console.log("*********************************************************************** \n"); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment