DUMMY.pm 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package Trog::Data::DUMMY;
  2. use 5.040;
  3. use re '/aasx';
  4. use warnings FATAL => 'all';
  5. use Carp qw{confess};
  6. use Errno();
  7. use Fcntl qw{O_WRONLY O_CREAT O_EXCL};
  8. use JSON::MaybeXS;
  9. use File::Slurper;
  10. use List::Util qw{uniq};
  11. use Path::Tiny();
  12. use parent qw{Trog::DataModule};
  13. =head1 WARNING
  14. Do not use this as a production data model. It is *not* safe to race conditions, and is only here for testing.
  15. =cut
  16. our $datastore = 'data/DUMMY.json';
  17. sub lang { return 'Perl Regex in Quotemeta' }
  18. sub help { return 'https://perldoc.perl.org/functions/quotemeta.html' }
  19. our $posts;
  20. sub read ( $self, $query = {} ) {
  21. # Seed an empty datastore, as one operation rather than a test followed by
  22. # a create. O_EXCL means a file that appeared in between is left alone
  23. # rather than truncated, and unlike the previous unchecked open, a failure
  24. # that is not EEXIST is reported here instead of surfacing as a confusing
  25. # 'print on closed filehandle' followed by a die inside read_text.
  26. if ( sysopen( my $fh, $datastore, O_WRONLY | O_CREAT | O_EXCL ) ) {
  27. print {$fh} '[]';
  28. close $fh;
  29. }
  30. elsif ( $! != Errno::EEXIST ) {
  31. confess "Could not create $datastore: $!";
  32. }
  33. my $slurped = File::Slurper::read_text($datastore);
  34. $posts = JSON::MaybeXS::decode_json($slurped);
  35. # Sort everything by date DESC
  36. @$posts = sort { $b->{created} <=> $a->{created} } @$posts;
  37. return $posts;
  38. }
  39. sub count ($self) {
  40. $posts //= $self->read();
  41. return scalar(@$posts);
  42. }
  43. sub write ( $self, $data, $overwrite = 0 ) {
  44. my $orig = [];
  45. if ($overwrite) {
  46. $orig = $data;
  47. }
  48. else {
  49. $orig = $self->read();
  50. push( @$orig, @$data );
  51. }
  52. open( my $fh, '>', $datastore ) or confess;
  53. print $fh JSON::MaybeXS::encode_json($orig);
  54. close $fh;
  55. return 1;
  56. }
  57. sub delete ( $self, @posts ) {
  58. my $example_posts = $self->read();
  59. foreach my $update (@posts) {
  60. @$example_posts = grep { $_->{id} ne $update->{id} } @$example_posts;
  61. }
  62. $self->write( $example_posts, 1 );
  63. return 0;
  64. }
  65. sub tags ($self) {
  66. return ( uniq map { @{ $_->{tags} } } @$posts );
  67. }
  68. 1;