Catalyst-Plugin-DetachIfNotModified

 view release on metacpan or  search on metacpan

lib/Catalyst/Plugin/DetachIfNotModified.pm  view on Meta::CPAN

package Catalyst::Plugin::DetachIfNotModified;

use v5.14;

# ABSTRACT: Short-circuit requests with If-Modified-Since headers

use Moose::Role;

use HTTP::Headers 5.18;
use HTTP::Status qw/ HTTP_NOT_MODIFIED /;
use List::Util qw/ max /;
use Ref::Util qw/ is_blessed_ref /;

# RECOMMEND PREREQ: Plack::Middleware::ConditionalGET
# RECOMMEND PREREQ: Ref::Util::XS

use namespace::autoclean;

our $VERSION = 'v0.3.1';


sub detach_if_not_modified_since {
    my ($c, @times) = @_;

    my @epochs = grep defined, map { is_blessed_ref($_) ? $_->epoch : $_ } @times;
    my $time = max(@epochs) // return;
    my $res  = $c->res;
    $res->headers->last_modified($time);

    my $hdr = $c->req->headers;
    if (my $since = $hdr->if_modified_since) {
        if ($since >= $time) {
            $res->code(HTTP_NOT_MODIFIED);
            $c->detach;
        }
    }
}


1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Catalyst::Plugin::DetachIfNotModified - Short-circuit requests with If-Modified-Since headers

=head1 VERSION

version v0.3.1

=head1 SYNOPSIS

In your Catalyst class:

  use Catalyst qw/
      DetachIfNotModified
    /;

In a controller method:

  my $item = ...

  $c->detach_if_not_modified_since( $item->timestamp );

  # Do some CPU-intensive stuff or generate response body here.

=head1 DESCRIPTION

This plugin will allow your L<Catalyst> app to handle requests with
C<If-Modified-Since> headers.



( run in 1.898 second using v1.01-cache-2.11-cpan-39bf76dae61 )