106 lines
2.5 KiB
Perl
106 lines
2.5 KiB
Perl
# This is the main class for compiled.world, it is instantiated every request
|
|
# Routes, database connections, and other data around the request lifecycle are passed
|
|
# as attributes, and should not be instantiated per request.
|
|
|
|
package CW;
|
|
|
|
use Moo;
|
|
use Plack::Request;
|
|
use Try::Tiny;
|
|
|
|
use feature 'state';
|
|
|
|
use CW::Plack::Request;
|
|
use CW::Plack::Response;
|
|
use CW::Migration;
|
|
|
|
has h => (
|
|
is => 'ro',
|
|
required => 1
|
|
);
|
|
|
|
has dbh => (
|
|
is => 'ro',
|
|
required => 1
|
|
);
|
|
|
|
has environment => (
|
|
is => 'ro',
|
|
required => 1
|
|
);
|
|
|
|
has router => (
|
|
is => 'ro',
|
|
required => 1
|
|
);
|
|
|
|
sub app {
|
|
my ($self) = @_;
|
|
return sub {
|
|
my ($env) = @_;
|
|
my $plack_request = Plack::Request->new($env);
|
|
|
|
my $request =
|
|
CW::Plack::Request->new( request => $plack_request, h => $self->h );
|
|
my $response = $request->new_response(200);
|
|
|
|
my $match = $self->router->match($env);
|
|
|
|
if ($match) {
|
|
my $route = $match->{route};
|
|
my $pkg = $route->pkg;
|
|
my $action = $route->action;
|
|
|
|
my %params = %$match;
|
|
delete $params{route};
|
|
|
|
try {
|
|
$pkg->new(
|
|
dbh => $self->dbh,
|
|
params => \%params,
|
|
request => $request,
|
|
response => $response
|
|
)->$action();
|
|
}
|
|
catch {
|
|
my $error = $_;
|
|
|
|
use DDP;
|
|
p $error;
|
|
|
|
state $show_errors = $self->environment ne 'prod';
|
|
if ( ref($error) && ref($error) eq 'HASH' && $error->{status} )
|
|
{
|
|
$response->status( $error->{status} );
|
|
$response->template(
|
|
"Error::" . $error->{status},
|
|
{
|
|
show_errors => $show_errors,
|
|
error => $error
|
|
}
|
|
);
|
|
}
|
|
else {
|
|
$response->status(500);
|
|
$response->template(
|
|
"Error::500",
|
|
{
|
|
show_errors => $show_errors,
|
|
error => $error
|
|
}
|
|
);
|
|
}
|
|
}
|
|
|
|
}
|
|
else {
|
|
$response->status(404);
|
|
$response->template("Error::404");
|
|
}
|
|
|
|
return $response->finalize;
|
|
}
|
|
}
|
|
|
|
1;
|