Commit d11902a4 authored by Luc Didry's avatar Luc Didry

Add cache system

This commit is dedicated to guilhemB, who is supporting me on Tipeee.
Many thanks :-)
parent dc72c4b1
......@@ -53,11 +53,30 @@ sub startup {
$self->secrets($config->{secret});
# Helpers
$self->helper(
cache => sub {
my $c = shift;
state $cache = {};
}
);
$self->helper(
clear_cache => sub {
my $c = shift;
my $cache = $c->cache;
my @keys = keys %{$cache};
my $limit = ($c->app->mode eq 'production') ? 500 : 1;
map {delete $cache->{$_};} @keys if (scalar(@keys) > $limit);
}
);
$self->helper(
ip => sub {
my $c = shift;
my $proxy = $c->req->headers->header('X-Forwarded-For');
my $ip = ($proxy) ? $proxy : $c->tx->remote_address;
my $c = shift;
my $proxy = $c->req->headers->header('X-Forwarded-For');
my $ip = ($proxy) ? $proxy : $c->tx->remote_address;
return $ip;
}
......
......@@ -203,9 +203,16 @@ sub get {
my $c = shift;
my $short = $c->param('short');
my @urls = LstuModel::Lstu->select('WHERE short = ?', $short);
if (scalar(@urls)) {
my $url = $urls[0]->url;
my ($url, @urls);
if (defined $c->cache->{$short}) {
$url = $c->cache->{$short}->{url};
} else {
@urls = LstuModel::Lstu->select('WHERE short = ?', $short);
if (scalar(@urls)) {
$url = $urls[0]->url;
}
}
if ($url) {
$c->respond_to(
json => { json => { success => Mojo::JSON->true, url => $url } },
any => sub {
......@@ -216,8 +223,18 @@ sub get {
);
# Update counter
$c->on(finish => sub {
if (defined $c->cache->{$short}) {
@urls = LstuModel::Lstu->select('WHERE short = ?', $short);
} else {
$c->cache->{$short} = {
last_used => time,
url => $url
};
}
my $counter = $urls[0]->counter + 1;
$urls[0]->update (counter => $counter);
$urls[0]->update(counter => $counter);
$c->clear_cache;
});
} else {
my $msg = $c->l('The shortened URL %1 doesn\'t exist.', $c->url_for('/')->to_abs.$short);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment