| 1 | package Magpie::Plugin::Resource::Cache; | ||
| 2 | $Magpie::Plugin::Resource::Cache::VERSION = '1.163200'; | ||
| 3 | use Moose::Role; | ||
| 4 | |||
| 5 | # ABSTRACT: A Role to add Caching to a Resource; | ||
| 6 | # | ||
| 7 | use Magpie::Constants; | ||
| 8 | |||
| 9 | requires qw(mtime); | ||
| 10 | |||
| 11 | has cache => ( | ||
| 12 | is => 'ro', | ||
| 13 | lazy_build => 1, | ||
| 14 | ); | ||
| 15 | |||
| 16 | around 'GET' => sub { | ||
| 17 | my $orig = shift; | ||
| 18 | my $self = shift; | ||
| 19 | my $mtime = $self->mtime; | ||
| 20 | my $uri = $self->request->uri->as_string; | ||
| 21 | |||
| 22 | if ( $mtime && $mtime > 0 ) { | ||
| 23 | my $data = $self->cache->get($uri); | ||
| 24 | if ($data && defined $data->{resource} && defined defined $data->{resource}->{mtime} && $mtime == $data->{resource}->{mtime}) { | ||
| 25 | my $content = $data->{content}; | ||
| 26 | $self->data($content); | ||
| 27 | return DONE; | ||
| 28 | } | ||
| 29 | else { | ||
| 30 | # actual content will be added at the end of the pipeline process | ||
| 31 | my $data = { content => '', resource => { mtime => $mtime,}}; | ||
| 32 | $self->cache->set($uri, $data); | ||
| 33 | $self->parent_handler->add_handler('Magpie::Component::ContentCache'); | ||
| 34 | } | ||
| 35 | } | ||
| 36 | |||
| 37 | return $self->$orig(@_); | ||
| 38 | }; | ||
| 39 | |||
| 40 | after [qw(add_dependency delete_dependency)] => sub { | ||
| 41 | my $self = shift; | ||
| 42 | my $uri = $self->request->uri->as_string; | ||
| 43 | my $data = $self->cache->get($uri); | ||
| 44 | |||
| 45 | unless ( $data ) { | ||
| 46 | $data = {}; | ||
| 47 | } | ||
| 48 | |||
| 49 | $data->{resource}->{dependencies} = $self->dependencies; | ||
| 50 | |||
| 51 | $self->cache->set($uri, $data); | ||
| 52 | }; | ||
| 53 | |||
| 54 | 1; | ||
| 55 | |||
| 56 | __END__ |