DUMMY.pm 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 parent qw{Trog::DataModule};
  10. =head1 WARNING
  11. Do not use this as a production data model. It is *not* safe to race conditions, and is only here for testing.
  12. =cut
  13. our $datastore = 'data/DUMMY.json';
  14. sub lang { 'Perl Regex in Quotemeta' }
  15. sub help { 'https://perldoc.perl.org/functions/quotemeta.html' }
  16. our $posts;
  17. sub read ($self, $query={}) {
  18. if ( !-f $datastore) {
  19. open(my $fh, '>', $datastore);
  20. print $fh '[]';
  21. close $fh;
  22. }
  23. my $slurped = File::Slurper::read_text($datastore);
  24. $posts = JSON::MaybeXS::decode_json($slurped);
  25. # Sort everything by date DESC
  26. @$posts = sort { $b->{created} <=> $a->{created} } @$posts;
  27. return $posts;
  28. }
  29. sub count ($self) {
  30. $posts //= $self->read();
  31. return scalar(@$posts);
  32. }
  33. sub write($self,$data,$overwrite=0) {
  34. my $orig = [];
  35. if ($overwrite) {
  36. $orig = $data;
  37. } else {
  38. $orig = $self->read();
  39. push(@$orig,@$data);
  40. }
  41. open(my $fh, '>', $datastore) or confess;
  42. print $fh JSON::MaybeXS::encode_json($orig);
  43. close $fh;
  44. }
  45. sub delete($self, @posts) {
  46. my $example_posts = $self->read();
  47. foreach my $update (@posts) {
  48. @$example_posts = grep { $_->{id} ne $update->{id} } @$example_posts;
  49. }
  50. $self->write($example_posts,1);
  51. return 0;
  52. }
  53. 1;