Created
August 15, 2012 00:47
-
-
Save clarle/3354295 to your computer and use it in GitHub Desktop.
Y.Cache as a quick in-memory database
This file contains 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> | |
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> | |
<script type="text/javascript"> | |
$(document).ready(function () { | |
$('#user-submit').click(function () { | |
var payload = { | |
name: $('#user-name').val(), | |
msg: $('#user-msg').val() | |
}; | |
$.ajax({ | |
url: "/users", | |
type: "POST", | |
contentType: "application/json", | |
processData: false, | |
data: JSON.stringify(payload), | |
complete: function (data) { | |
$('#output').html(data.responseText); | |
} | |
}); | |
}); | |
$('#left-submit').click(function () { | |
var url = "/messages/" + $('#left-name').val(); | |
$.ajax({ | |
url: url, | |
complete: function (data) { | |
$('#output').html(data.responseText); | |
} | |
}); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<h3>Enter a username and message to enter into the database:</h3> | |
<input id="user-name" type="text" placeholder="Username"/> | |
<input id="user-msg" type="text" placeholder="Message"/> | |
<input id="user-submit" type="submit" /> | |
<h3>Enter a username to get the message they left:</h3> | |
<input id="left-name" type="text" placeholder="Username"/> | |
<input id="left-submit" type="submit" /> | |
<p id="output"></p> | |
</body> | |
</html> |
This file contains 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 express = require('express'), | |
Y = require('yui/cache'); | |
var app = module.exports = express(); | |
// Database setup | |
var db = new Y.Cache({max: 5}); | |
// Configuration | |
app.use(express.bodyParser()); | |
// Main route sends our HTML file | |
app.get('/', function(req, res) { | |
res.sendfile(__dirname + '/index.html'); | |
}); | |
// Get our messages | |
app.get('/messages/:user', function (req, res) { | |
var data = db.retrieve(req.params.user); | |
res.send(req.params.user + ' said: ' + data.response); | |
}); | |
// Update database | |
app.post('/users', function (req, res) { | |
db.add(req.body.name, req.body.msg); | |
res.send(req.body.name + ' was added to the database'); | |
}); | |
// Begin listening | |
app.listen(3000); | |
console.log('Server running!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment