DUMMY.pm 1.5 KB

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