Created
December 29, 2011 17:50
-
-
Save monken/1535250 to your computer and use it in GitHub Desktop.
MyApp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package MyApp::Controller; | |
use Moose; | |
use IO::All; | |
use JSON::XS; | |
use Plack::Response; | |
use MIME::Base64 qw(encode_base64url decode_base64url); | |
has [qw(model req res)] => ( is => 'ro' ); | |
sub run { | |
my ($self) = @_; | |
my $res = $self->res; | |
my $cv; | |
if ( $self->req->path_info eq '/' ) { | |
$cv = $self->create; | |
} | |
elsif ( $self->req->path_info =~ /^\/+(.+)\/?$/ ) { | |
$cv = $self->get($1); | |
} | |
return sub { | |
my $response = shift; | |
$cv->cb( | |
sub { | |
$res->body( shift->recv ); | |
$response->( $res->finalize ); | |
} | |
); | |
}; | |
} | |
sub create { | |
my $self = shift; | |
$self->res->header( 'Content-Type' => 'application/json' ); | |
my $cv = AE::cv; | |
my $body = eval { decode_json( $self->req->content ) }; | |
$body ||= {}; | |
$self->model->new_queue->cb( | |
sub { | |
my $queue = shift->recv->method_frame->queue; | |
my $job = { | |
id => encode_base64url($queue), | |
reply_to => $queue, | |
timestamp => time, | |
%$body, | |
}; | |
$self->model->publish($job); | |
$cv->send( encode_json($job) ); | |
} | |
); | |
return $cv; | |
} | |
sub get { | |
my ( $self, $id ) = @_; | |
$self->res->header( 'Content-Type' => 'application/pdf' ); | |
my $cv = AE::cv; | |
my $file = "var/$id.pdf"; | |
$cv->send(io($file)) && return $cv if ( -e $file ); | |
my $queue = decode_base64url($id); | |
$self->model->consume($queue)->cb( sub { $cv->send( io($file) ) } ); | |
return $cv; | |
} | |
package MyApp; | |
use Moose; | |
use Plack::Request; | |
sub { | |
MyApp::Controller->new( | |
model => MyApp::Model->new, | |
req => Plack::Request->new(@_), | |
res => Plack::Response->new(200), | |
)->run; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment