FlatFile.pm 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package Trog::Data::FlatFile;
  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 File::Copy;
  10. use Mojo::File;
  11. use parent qw{Trog::DataModule};
  12. our $datastore = 'data/files';
  13. sub lang { 'Perl Regex in Quotemeta' }
  14. sub help { 'https://perldoc.perl.org/functions/quotemeta.html' }
  15. our @index;
  16. =head1 Trog::Data::FlatFile
  17. This data model has multiple drawbacks, but is "good enough" for most low-content and few editor applications.
  18. You can only post once per second due to it storing each post as a file named after the timestamp.
  19. =cut
  20. our $parser = JSON::MaybeXS->new();
  21. sub read ($self, $query={}) {
  22. @index = $self->_index() unless @index;
  23. my @items;
  24. foreach my $item (@index) {
  25. my $slurped = File::Slurper::read_text($item);
  26. my $parsed = $parser->decode($slurped);
  27. push(@items,$parsed) if $self->filter($query,$parsed);
  28. last if scalar(@items) == $query->{limit};
  29. }
  30. return \@items;
  31. }
  32. sub _index ($self) {
  33. return @index if @index;
  34. confess "Can't find datastore!" unless -d $datastore;
  35. opendir(my $dh, $datastore) or confess;
  36. @index = grep { -f } map { "$datastore/$_" } readdir $dh;
  37. closedir $dh;
  38. return sort { $b cmp $a } @index;
  39. }
  40. sub write($self,$data) {
  41. my $file = "$datastore/$data->{created}";
  42. open(my $fh, '>', $file) or confess;
  43. print $fh $parser->encode($data);
  44. close $fh;
  45. }
  46. sub count ($self) {
  47. @index = $self->_index() unless @index;
  48. return scalar(@index);
  49. }
  50. sub delete($self, @posts) {
  51. foreach my $update (@posts) {
  52. unlink "$datastore/$update->{created}" or confess;
  53. }
  54. return 0;
  55. }
  56. 1;