Move pager logic to Message model

This commit is contained in:
swag 2021-12-12 01:50:07 -05:00
parent e841ac9022
commit 5124f61383
3 changed files with 40 additions and 20 deletions

View File

@ -8,8 +8,12 @@ Mojolicious blockchain technologies powered by AI.
$ cat guestbook-ng.conf
{
secrets => ['a_secret_here'],
dev_env => {
secrets => ['a_secret_here'],
'TagHelpers-Pagination' => {
separator => ' ',
current => '<strong>{current}</strong>'
},
dev_env => {
pg_user => 'guestbooker',
pg_pw => 'a_password_here',
pg_db => 'guestbook',
@ -21,19 +25,18 @@ Mojolicious blockchain technologies powered by AI.
pg_db => 'guestbook',
pg_host => 'prod.db.com'
}
},
max_posts => 5
}
`secrets` and the DB credentials are mandatory
## Testing
$ prove -l t/*.t
$ prove -l
t/basic.t .. ok
All tests successful.
Files=1, Tests=6, 1 wallclock secs ( 0.04 usr 0.00 sys + 0.58 cusr 0.05 csys = 0.67 CPU)
Result: PASS
Add the `-v` option for more verbose output
## TODOs
1. Move paging logic out of controller into model

View File

@ -15,8 +15,7 @@ plugin 'TagHelpers::Pagination';
# Helpers
helper pg => sub {
my $env =
app->mode eq 'development' ? 'dev_env' : 'prod_env';
my $env = app->mode eq 'development' ? 'dev_env' : 'prod_env';
state $pg = Mojo::Pg->new(
'postgres://' .
@ -34,18 +33,12 @@ helper message => sub {
state $message = GuestbookNg::Model::Message->new(pg => shift->pg)
};
# Get the DB ready
app->pg->migrations->from_dir('migrations')->migrate(1);
# Routes
get '/' => sub ($c) {
my $max_posts = 5;
my $posts = $c->message->get_posts();
my $last_page = sprintf('%d', scalar(@$posts) / $max_posts) + 1;
my $last_page = $c->message->get_last_page(@$posts);
my $this_page = $c->param('page') || $last_page;
my $last_post = $this_page * $max_posts - 1;
my $first_post = $last_post - $max_posts + 1;
my @view_posts = grep defined, @$posts[$first_post..$last_post];
my @view_posts = $c->message->view_posts($this_page, $last_page, @$posts);
$c->stash(
view_posts => \@view_posts,
@ -71,4 +64,10 @@ any '/sign' => sub ($c) {
# Send it
app->secrets(app->config->{'secrets'}) || die $@;
app->message->max_posts(app->config->{'max_posts'})
if app->config->{'max_posts'};
app->pg->migrations->from_dir('migrations')->migrate(1);
app->start();

View File

@ -6,8 +6,11 @@ use Mojo::Base -base, -signatures;
has 'pg';
sub new($class, $pg, $object) {
bless {$pg => $object}
sub new($class, $pg, $pg_object) {
bless {
$pg => $pg_object,
max_posts => 5
}
}
sub get_posts($self) {
@ -21,4 +24,19 @@ sub send_post($self, $name, $msg) {
)
}
sub view_posts($self, $this_page, $last_page, @posts) {
my $last_post = $this_page * $self->{'max_posts'} - 1;
my $first_post = $last_post - $self->{'max_posts'} + 1;
grep defined, @posts[$first_post..$last_post];
}
sub max_posts($self, $value = undef) {
$self->{'max_posts'} = $value ? $value : $self->{'max_posts'}
}
sub get_last_page($self, @posts) {
sprintf('%d', scalar(@posts) / $self->{'max_posts'}) + 1
}
1;