Created
January 5, 2017 02:14
-
-
Save jberger/0963d5e31b8378030fde5827e386beac to your computer and use it in GitHub Desktop.
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
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment