Skip to content

Instantly share code, notes, and snippets.

@8bitDesigner
Last active December 16, 2015 12:49
Show Gist options
  • Select an option

  • Save 8bitDesigner/5437600 to your computer and use it in GitHub Desktop.

Select an option

Save 8bitDesigner/5437600 to your computer and use it in GitHub Desktop.

Tiny chat app powered by CouchDB

This was cloned off of some work by the fantastic Max Odgen, and does a great job of showing what CouchDB can do.

Messages in the by_time view:

Client side display

{
"_id": "_design/talk",
"_rev": "7-ee931dd9b9afff7352385c55d917cfe5",
"views": {
"by_time": {
"map": "function(doc) {\n if (doc.created_at && doc.message) {\n emit(doc.created_at, doc.message);\n }\n}"
}
},
"_attachments": {
"index.html": {
"content_type": "text/html",
"revpos": 7,
"digest": "md5-LdXRObv8WfssOGqiEEQkFA==",
"length": 1432,
"stub": true
}
}
}
<!DOCTYPE html>
<html>
<head><title>Tiny CouchApp</title></head>
<body>
<h1>Tiny CouchApp</h1>
<form id="new_message">
<label for="message">Message:</label>
<input type="text" name="message" value="">
<p><input type="submit" value="Save &rarr;"></p>
</form>
<ul id="messages"></ul>
</body>
<script src="/_utils/script/jquery.js"></script>
<script src="/_utils/script/jquery.couch.js"></script>
<script>
$(function() {
// make sure this matches the name of your database
var db = $.couch.db("talk");
$("#new_message").submit(function() {
// save the message to couchdb
var doc = {}, input = $("input[name=message]", this);
doc.message = input.val();
doc.created_at = new Date();
db.saveDoc(doc, {
success : function(r) {
input.val("");
}
});
return false;
});
function redrawMessages() {
// make sure this matches the name of your map view
db.view("talk/by_time", {
descending : true,
success : function(resp) {
var list = $("#messages");
list.empty();
resp.rows.forEach(function(row) {
list.append($('<li/>').text(row.value));
});
}
})
};
redrawMessages();
var changeHandler = db.changes();
changeHandler.onChange(redrawMessages);
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment