Skip to content

Commit

Permalink
add Annotation and 'cacheable'
Browse files Browse the repository at this point in the history
  • Loading branch information
rawleyfowler committed Aug 4, 2023
1 parent 5dc9ae8 commit 4fbd352
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
13 changes: 13 additions & 0 deletions examples/cache/app.pl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use 5.036;

use Slick;
use Slick::Annotation qw(cacheable);

my $s = Slick->new;

Expand All @@ -20,6 +21,7 @@

$s->cache('my_redis')->set( something => 'awesome' );

# Use your cache
$s->get(
'/foo' => sub {
my ( $app, $context ) = @_;
Expand All @@ -28,4 +30,15 @@
}
);

# Use your cache to cache your route
$s->get(
'/foobar' => cacheable(
'my_redis',
sub {
my ( $app, $context ) = @_;
return $context->json( { foo => 'bar' } );
}
)
);

$s->run;
52 changes: 52 additions & 0 deletions lib/Slick/Annotation.pm
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package Slick::Annotation;

use 5.036;

use Exporter qw(import);
use Carp qw(carp);
use JSON::Tiny qw(decode_json encode_json);
use Scalar::Util qw(blessed);

our @EXPORT_OK = qw(cacheable);

sub cacheable {
my $cache = shift;
my $code = shift;
my $timeout = shift // 300; # Default cache is 5 minutes

return sub {
my ( $app, $context ) = @_;

state $cache_obj = $app->cache($cache);

if ($cache_obj) {
if ( $cache_obj->get( $context->request->uri ) ) {
my $response =
decode_json( $cache_obj->get( $context->request->uri ) );

$context->from_psgi($response);
}
else {
$code->( $app, $context );

my $json = encode_json $context->to_psgi;

if ( blessed( $cache_obj->{_executor} ) =~ /Memcached/x ) {
$cache_obj->set(
$context->request->uri => $json => $timeout );
}
else {
$cache_obj->set(
$context->request->uri => $json => EX => $timeout );
}
}
}
else {
carp
qq{Attempted to use cache $cache to cache route but cache does not exist.};
$code->( $app, $context );
}
}
}

1;
11 changes: 11 additions & 0 deletions lib/Slick/Context.pm
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,17 @@ sub to_psgi {
return [ $response->{status}, $response->{headers}, $response->{body} ];
}

sub from_psgi {
my $self = shift;
my $response = shift;

$self->response->{status} = $response->[0];
$self->response->{headers} = $response->[1];
$self->response->{body} = $response->[2];

return $self;
}

sub redirect {
my ( $self, $location, $status ) = @_;

Expand Down

0 comments on commit 4fbd352

Please sign in to comment.