Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Added message persistence

  • Loading branch information...
commit 2ced3d496d5fb8d6a82a317550c846f0b926d3e0 1 parent 41e5c43
Pat Patterson authored June 10, 2011

Showing 1 changed file with 27 additions and 0 deletions. Show diff stats Hide diff stats

  1. 27  server.js
27  server.js
@@ -18,11 +18,37 @@ var fu = require("./fu"),
18 18
 
19 19
 var MESSAGE_BACKLOG = 200,
20 20
     SESSION_TIMEOUT = 60 * 1000;
  21
+    
  22
+var pg = require('pg').native; //native libpq bindings = `var pg = require('pg').native`
  23
+var conString = process.env.DATABASE_URL || "tcp://postgres:1234@localhost/postgres";
  24
+
  25
+var client = new pg.Client(conString);
  26
+client.connect();
  27
+
  28
+client.query("CREATE TABLE chat_messages(nick varchar(50), type varchar(10), text varchar(1024), timestamp bigint)", 
  29
+    function(err, result) {
  30
+        if (err) {
  31
+            if (err.code === '42P07') {
  32
+                console.log("chat_messages table already exists");
  33
+            } else {
  34
+                console.log(err);
  35
+            }
  36
+        } else {
  37
+            console.log("created chat_messages table");
  38
+        }
  39
+    });
21 40
 
22 41
 var channel = new function () {
23 42
   var messages = [],
24 43
       callbacks = [];
  44
+      
  45
+  var query = client.query("SELECT * FROM chat_messages ORDER BY timestamp LIMIT $1", [MESSAGE_BACKLOG]);
25 46
 
  47
+  query.on('row', function(row) {
  48
+    console.log(row);
  49
+    messages.push(row);
  50
+  });
  51
+  
26 52
   this.appendMessage = function (nick, type, text) {
27 53
     var m = { nick: nick
28 54
             , type: type // "msg", "join", "part"
@@ -43,6 +69,7 @@ var channel = new function () {
43 69
     }
44 70
 
45 71
     messages.push( m );
  72
+    client.query("INSERT INTO chat_messages(nick, type, text, timestamp) values($1, $2, $3, $4)",    [m.nick, m.type, m.text, m.timestamp]);
46 73
 
47 74
     while (callbacks.length > 0) {
48 75
       callbacks.shift().callback([m]);

0 notes on commit 2ced3d4

Please sign in to comment.
Something went wrong with that request. Please try again.