DUMMY.pm 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. } else {
  40. $orig = $self->read();
  41. push(@$orig,@$data);
  42. }
  43. open(my $fh, '>', $datastore) or confess;
  44. print $fh JSON::MaybeXS::encode_json($orig);
  45. close $fh;
  46. }
  47. sub delete($self, @posts) {
  48. my $example_posts = $self->read();
  49. foreach my $update (@posts) {
  50. @$example_posts = grep { $_->{id} ne $update->{id} } @$example_posts;
  51. }
  52. $self->write($example_posts,1);
  53. # Gorilla cache invalidation
  54. Path::Tiny::path('www/statics')->remove_tree;
  55. return 0;
  56. }
  57. sub tags($self) {
  58. return (uniq map { @{$_->{tags}} } @$posts);
  59. }
  60. 1;