Implement basic guestbook signing and reading

This commit is contained in:
swagg boi 2021-12-05 02:52:31 -05:00
parent 9c0d077266
commit edca297f78
6 changed files with 76 additions and 7 deletions

View file

@ -27,5 +27,6 @@ Add the `-v` option for more verbose output
## TODOs
1. Create hostname k/v pair in conf file
1. Create rows in table
1. Add tests for `/post` route
1. Probably rename `/post` to `/sign`
1. Remove the Test model and clean up

View file

@ -7,6 +7,8 @@ use Mojolicious::Lite -signatures;
use Mojo::Pg;
use lib 'lib';
use GuestbookNg::Model::Test;
use GuestbookNg::Model::Message;
use Data::Dumper; # Uncomment for debugging
# Plugins
plugin 'Config';
@ -30,7 +32,7 @@ helper test => sub {
};
helper message => sub {
state $test = GuestbookNg::Model::Message->new(pg => shift->pg)
state $message = GuestbookNg::Model::Message->new(pg => shift->pg)
};
# Routes
@ -39,7 +41,9 @@ under sub ($c) {
};
get '/' => sub ($c) {
$c->render()
my $posts = $c->message->get_posts();
$c->render(posts => $posts);
} => 'index';
any '/test' => sub ($c) {
@ -55,5 +59,18 @@ any '/test' => sub ($c) {
);
};
any '/post' => sub ($c) {
if ($c->req->method() eq 'POST') {
my $name = $c->param('name');
my $message = $c->param('message');
$c->message->send_post($name, $message);
$c->redirect_to('index');
}
else {
$c->render()
}
};
# Send it
app->start();

View file

@ -10,4 +10,15 @@ sub new($class, $pg, $object) {
bless {$pg => $object}
}
sub get_posts($self) {
$self->pg->db->query('SELECT date, name, msg FROM messages;')->arrays()
}
sub send_post($self, $name, $msg) {
$self->pg->db->query(
'INSERT INTO messages (date, name, msg)
VALUES (NOW(), ?, ?);', $name, $msg
)
}
1;

View file

@ -1,3 +1,20 @@
% layout 'default';
% title 'Home';
<h2>Welcome to the Mojolicious real-time web framework!</h2>
<h2>Messages from the World Wide Web</h2>
<% for my $row (reverse @$posts) { %>
<table>
<tr>
<th>Date:</th>
<td><%= @$row[0] %></td>
</tr>
<tr>
<th>Name:</th>
<td><%= @$row[1] %></td>
</tr>
<tr>
<th>Message:</th>
<td><%= @$row[2] %></td>
</tr>
</table>
<br>
<% } %>

View file

@ -5,7 +5,7 @@
</head>
<body>
<center>
<h1><%= title %></h1>
<h1>Guestbook-NG</h1>
<!-- Nav table -->
<table>
<tr>
@ -13,10 +13,14 @@
<td>&nbsp;</td>
<td><%= link_to Test => 'test' %></td>
<td>&nbsp;</td>
<td><%= link_to Post => 'post' %></td>
<td><%= link_to Sign => 'post' %></td>
</tr>
</table>
<%= content %>
<footer>
<p><i>Maximize your dynamic innovation using battle-tested deep
learning models.</i></p>
</footer>
</center>
</body>
</html>

19
templates/post.html.ep Normal file
View file

@ -0,0 +1,19 @@
% layout 'default';
% title 'New Post';
<h2>Create a New Post</h2>
<form method="post">
<table>
<tr>
<th>Name:</th>
<td><%= input_tag 'name' %></td>
</tr>
<tr>
<th>Message:</th>
<td><%= text_area 'message', cols => 40, rows => 6 %></td>
</tr>
<tr>
<th>&nbsp;</th>
<td><%= submit_button 'Send it' %></td>
</tr>
</table>
</form>