DUMMY.pm 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 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 { return 'Perl Regex in Quotemeta' }
  17. sub help { return 'https://perldoc.perl.org/functions/quotemeta.html' }
  18. our $posts;
  19. sub read ( $, $ = {} ) {
  20. # Seed an empty datastore, as one operation rather than a test followed by
  21. # a create. O_EXCL means a file that appeared in between is left alone
  22. # rather than truncated, and unlike the previous unchecked open, a failure
  23. # that is not EEXIST is reported here instead of surfacing as a confusing
  24. # 'print on closed filehandle' followed by a die inside read_text.
  25. if ( sysopen( my $fh, $datastore, O_WRONLY | O_CREAT | O_EXCL ) ) {
  26. print {$fh} '[]';
  27. close $fh;
  28. }
  29. elsif ( $! != Errno::EEXIST ) {
  30. confess "Could not create $datastore: $!";
  31. }
  32. my $slurped = File::Slurper::read_text($datastore);
  33. $posts = JSON::MaybeXS::decode_json($slurped);
  34. # Sort everything by date DESC
  35. @$posts = sort { $b->{created} <=> $a->{created} } @$posts;
  36. return $posts;
  37. }
  38. sub count ($self) {
  39. $posts //= $self->read();
  40. return scalar(@$posts);
  41. }
  42. sub write ( $self, $data, $overwrite = 0 ) {
  43. my $orig = [];
  44. if ($overwrite) {
  45. $orig = $data;
  46. }
  47. else {
  48. $orig = $self->read();
  49. push( @$orig, @$data );
  50. }
  51. open( my $fh, '>', $datastore ) or confess;
  52. print $fh JSON::MaybeXS::encode_json($orig);
  53. close $fh;
  54. return 1;
  55. }
  56. sub delete ( $self, @posts ) {
  57. my $example_posts = $self->read();
  58. foreach my $update (@posts) {
  59. @$example_posts = grep { $_->{id} ne $update->{id} } @$example_posts;
  60. }
  61. $self->write( $example_posts, 1 );
  62. return 0;
  63. }
  64. sub tags ($) {
  65. return ( uniq map { @{ $_->{tags} } } @$posts );
  66. }
  67. 1;