packageTrace;useMojo::Base'Mojo::Pg';useFile::Tempqw(tempfile);useMojo::Utilqw(spurt);my%h;sub_enqueue{my$dbh=pop;my$h=delete$h{$dbh};spurt(${$h->{trace}},$h->{filename});warn("filename: $$h{filename}");shift->SUPER::_enqueue($dbh);}sub_dequeue{my$dbh=shift->SUPER::_dequeue(@_);my($fh,$trace);my(undef,$filename)=tempfile("pg_trace_XXXXXX",TMPDIR=>1,UNLINK=>0,SUFFIX=>".log");open($fh,"+>:scalar",\$trace);$dbh->trace(1,$fh);$h{$dbh}={};$h{$dbh}{fh}=$fh;$h{$dbh}{trace}=\$trace;$h{$dbh}{filename}=$filename;warn("filename: $filename");return$dbh;}packagemain;useMojolicious::Lite;usePerlIO::via::DBLog;useDBLog;helperpg=>sub{state$pg=Trace->new("postgresql://$ENV{DBI_USER}:$ENV{DBI_PASS}\@127.0.0.1/test")};get'/'=>'chat';websocket'/channel'=>sub{my$c=shift;$c->inactivity_timeout(3600);# Forward messages from the browser to PostgreSQL$c->on(message=>sub{my$c=shift;my$msg=shift;$c->pg->db->query('insert into log (text) values (?)',$msg);$c->pg->pubsub->notify(mojochat=>$msg)});# Forward messages from PostgreSQL to the browsermy$cb=$c->pg->pubsub->listen(mojochat=>sub{$c->send(pop)});$c->on(finish=>sub{shift->pg->pubsub->unlisten(mojochat=>$cb)});};app->pg->db->query('create table IF NOT EXISTS log (id serial primary key, text text)');app->start;__DATA__@@chat.html.ep<formonsubmit="sendChat(this.children[0]); return false"><input></form><divid="log"></div><script>varws=newWebSocket('<%= url_for('channel')->to_abs %>');ws.onmessage=function(e){document.getElementById('log').innerHTML+='<p>'+e.data+'</p>';};functionsendChat(input){ws.send(input.value);input.value=''}</script>
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.