add insert script

This commit is contained in:
Rawley Fowler
2023-07-11 15:54:26 -06:00
parent 28f919d8d7
commit c0803dc3da
4 changed files with 36 additions and 62 deletions

3
.gitignore vendored
View File

@@ -5,6 +5,7 @@ esy.lock/
*.db
*.pem
*~
posts/*
posts/*.blog
posts/*.post
\#*
@@ -12,4 +13,4 @@ posts/*.post
bookshelf.txt
site.db*
less/cache/
*.secret
*.secret

34
insert.pl Executable file
View File

@@ -0,0 +1,34 @@
#!/usr/bin/env perl
use strict;
use warnings;
use Carp qw(croak);
use Mojo::SQLite;
use Mojo::File;
use feature qw(say);
my $db = Mojo::SQLite->new('sqlite:site.db')->db;
my $title = shift || croak 'Expected $1 to be title';
my $slug = shift || croak 'Expected $2 to be slug';
my $content = shift || croak 'Expected $3 to be md file';
$content = Mojo::File->new($content)->slurp;
my $post = {
title => $title,
slug => $slug,
content => $content
};
if ( my $old_post = $db->select( 'posts', ['id'], { slug => $slug } )->hash ) {
say 'Updating post.';
$db->update( 'posts', $post, { id => $old_post->{id} } );
}
else {
say 'Inserting post.';
$db->insert( 'posts', $post );
}
say 'Finished.';

24
site.pl
View File

@@ -6,12 +6,6 @@ use Mojo::SQLite;
use Mojo::File;
use Carp qw(croak);
my $AUTH_HEADER = [ split( /,/, Mojo::File->new('.secret')->slurp ) ]->[0];
my $AUTH_KEY = [ split( /,/, Mojo::File->new('.secret')->slurp ) ]->[1];
croak qq{No AUTH_HEADER value in .secret} unless $AUTH_HEADER;
croak qq{No AUTH_KEY value in .secret} unless $AUTH_KEY;
my $sql = Mojo::SQLite->new('sqlite:site.db');
helper db => sub { state $db = $sql->db };
@@ -60,24 +54,6 @@ get '/blog/:post' => sub {
$c->render( template => 'post' );
};
post '/blog' => sub {
my $c = shift;
my $auth = $c->req->headers->to_hash->{$AUTH_HEADER};
return $c->rendered(400) unless $auth and ( $auth eq $AUTH_KEY );
if ( my $old_post =
$c->db->select( 'posts', ['id'], { slug => $c->req->json->{slug} } )
->hash )
{
$c->db->update( 'posts', $c->req->json, { id => $old_post->{id} } );
$c->rendered(204);
}
else {
$c->db->insert( 'posts', $c->req->json );
$c->rendered(201);
}
};
app->start;
__DATA__

View File

@@ -1,37 +0,0 @@
#!/usr/bin/env perl
use strict;
use warnings;
use Mojo::UserAgent;
use Mojo::File;
use Carp qw(croak carp);
my $file = Mojo::File->new(shift)
|| croak q{Expected $1 to be a file path, or couldn't open file};
my $ua = Mojo::UserAgent->new;
my $hn = shift || croak q{Expected $2 to be header name};
my $pw = shift || croak q{Expected $3 to be password};
my $ti = shift || croak q{Expected $4 to be title};
my $sl = shift || croak q{Expected $5 to be slug};
my $uri =
$ENV{BLOG_DEVELOPMENT} ? 'http://localhost:3000' : 'https://rawley.xyz';
my $j = {
content => $file->slurp,
title => $ti,
slug => $sl
};
my $r =
$ua->post( ( $uri . '/blog' ) => { $hn => $pw } => json => $j )->result;
if ( $r->is_success ) {
print 'Upload successful';
}
else {
carp q{Failed to upload } . $r->code;
exit 1;
}