#!/usr/bin/env perl
use Mojolicious::Lite;
use Mojo::JSON;
use Data::Dumper;
use 5.010;
app->renderer->add_helper(
action => sub {
my ( $self, $action ) = @_;
state $Actions = {
location => { mtime => 0 },
speakers => { mtime => 0 },
talks => { mtime => 0 },
interests => { mtime => 0 },
users => { mtime => 0 },
};
return if !exists $Actions->{$action};
my $path = app->home->rel_file( 'data/' . $action );
my $mtime = ( stat $path )[9];
if ( $mtime != $Actions->{$action}{mtime} ) {
open my $fh, $path or die "Couldn't open [$path]: $!";
my $content = do { local $/; <$fh> };
close $fh;
my $json = Mojo::JSON->new;
my $data = $json->decode($content);
if ( $json->error ) {
die $json->error;
}
$Actions->{$action} = {
mtime => $mtime,
data => $data,
};
}
return $Actions->{$action}{data};
}
);
get '/' => 'index';
get '/api/:action' => sub {
my $self = shift;
my $data = $self->helper( 'action', $self->stash('action') );
return if !ref $data;
my @data = @{$data};
foreach my $param ( $self->param ) {
my $value = $self->param($param);
@data = grep { ( !exists $_->{$param} ) || $value ~~ $_->{$param} }
@data;
}
$self->render_json( \@data );
};
app->start;
__DATA__
@@ index.html.ep
% layout 'default';
Please try /api/action
@@ layouts/default.html.ep
<!doctype html><html>
<head><title>Test OpenAMD API!</title></head>
<body><%== content %></body>
</html>
@@ exception.html.ep
<!doctype html><html>
<head><title>Exception</title></head>
<body><%== $exception %></body>
</html>