DUMMY.pm 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package Trog::Data::DUMMY;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures};
  6. use Carp qw{confess};
  7. use JSON::MaybeXS;
  8. use File::Slurper;
  9. use List::Util qw{uniq};
  10. use Path::Tiny();
  11. use parent qw{Trog::DataModule};
  12. =head1 WARNING
  13. Do not use this as a production data model. It is *not* safe to race conditions, and is only here for testing.
  14. =cut
  15. our $datastore = 'data/DUMMY.json';
  16. sub lang { 'Perl Regex in Quotemeta' }
  17. sub help { 'https://perldoc.perl.org/functions/quotemeta.html' }
  18. our $posts;
  19. sub read ( $self, $query = {} ) {
  20. if ( !-f $datastore ) {
  21. open( my $fh, '>', $datastore );
  22. print $fh '[]';
  23. close $fh;
  24. }
  25. my $slurped = File::Slurper::read_text($datastore);
  26. $posts = JSON::MaybeXS::decode_json($slurped);
  27. # Sort everything by date DESC
  28. @$posts = sort { $b->{created} <=> $a->{created} } @$posts;
  29. return $posts;
  30. }
  31. sub count ($self) {
  32. $posts //= $self->read();
  33. return scalar(@$posts);
  34. }
  35. sub write ( $self, $data, $overwrite = 0 ) {
  36. my $orig = [];
  37. if ($overwrite) {
  38. $orig = $data;
  39. }
  40. else {
  41. $orig = $self->read();
  42. push( @$orig, @$data );
  43. }
  44. open( my $fh, '>', $datastore ) or confess;
  45. print $fh JSON::MaybeXS::encode_json($orig);
  46. close $fh;
  47. }
  48. sub delete ( $self, @posts ) {
  49. my $example_posts = $self->read();
  50. foreach my $update (@posts) {
  51. @$example_posts = grep { $_->{id} ne $update->{id} } @$example_posts;
  52. }
  53. $self->write( $example_posts, 1 );
  54. # Gorilla cache invalidation
  55. Path::Tiny::path('www/statics')->remove_tree;
  56. return 0;
  57. }
  58. sub tags ($self) {
  59. return ( uniq map { @{ $_->{tags} } } @$posts );
  60. }
  61. 1;