Skip to content

Instantly share code, notes, and snippets.

@jberger
Last active November 6, 2016 20:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/8d09d4fa19aa54cff2d999c614380da3 to your computer and use it in GitHub Desktop.
Save jberger/8d09d4fa19aa54cff2d999c614380da3 to your computer and use it in GitHub Desktop.
use Mojolicious::Lite;
use Mojo::Pg;
helper pg => sub { state $pg = Mojo::Pg->new('postgresql://test:test@/test') };
get '/' => 'chat';
websocket '/channel' => sub {
my $c = shift;
$c->inactivity_timeout(3600);
# Forward messages from the browser to PostgreSQL
$c->on(message => sub { shift->pg->pubsub->notify(mojochat => shift) });
# Forward messages from PostgreSQL to the browser
my $cb = $c->pg->pubsub->listen(mojochat => sub { $c->send(pop) });
$c->on(finish => sub { shift->pg->pubsub->unlisten(mojochat => $cb) });
};
app->start;
__DATA__
@@ chat.html.ep
%= javascript 'https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.5/vue.js'
<div id="chat">
Username: <input v-model="username"><br>
Send: <input @keydown.enter="send" v-model="current"><br>
<div id="log"><p v-for="m in messages">{{m.username}}: {{m.message}}</p></div>
</div>
<script>
var ws = new WebSocket('<%= url_for('channel')->to_abs %>');
var vm = new Vue({
el: '#chat',
data: {
current: '',
messages: [],
username: '',
},
methods: {
send: function() {
ws.send(JSON.stringify({username: this.username, message: this.current}));
this.current = '';
},
},
});
ws.onmessage = function (e) { vm.messages.push(JSON.parse(e.data)) };
</script>
@jberger
Copy link
Author

jberger commented May 13, 2016

This is a version of https://gist.github.com/jberger/c4515eb8399f356736528dbc5af115f2 which uses richer data formatting (read: JSON)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment