summaryrefslogtreecommitdiff
path: root/lib/DeWeave/Collection.pm
blob: 6ad87eb78605607acbe910638285531e7b1b373c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package DeWeave::Collection; 
use Moose;
use namespace::autoclean;
use MooseX::Types::Moose qw(ArrayRef);
use JSON::Any;
use Try::Tiny;
use DeWeave::EDO;
use Lingua::EN::Inflect::Number 'to_S';
use Log::Log4perl ':easy';
use Data::Dump 'pp';
 
has items => (
    isa => ArrayRef['DeWeave::WBO'],
    is => 'ro',
    required => 1,
);
 
sub _local_part {
    my ($class) = @_;
    my ($sub) = ($class =~ m{^DeWeave::Collection::(\w+)});
    return $sub;
}
 
sub item_class {
    my ($class) = @_;
    my $sub = ucfirst(to_S(lc($class->_local_part)));
    return "DeWeave::BO::$sub" if $sub;
    return 'DeWeave::WBO'
}
 
sub items_path {
    my ($class) = @_;
    my $sub = lc($class->_local_part);
    return "storage/$sub";
}
 
sub from_json {
    my ($class,$json,$crypt)=@_;
 
    my $j = JSON::Any->new;
 
    my $args = $j->decode($json);
 
DEBUG '$args ',{filter=>\&pp,value=>$args};
 
    my @items;
 
    for my $input_item (@$args) {
        my $item;
        try {
            $item = $class->item_class->new({%$input_item,__crypt=>$crypt})
        }
        catch {
            die $_ unless ref($_) && $_->isa('DeWeave::Exception::Deleted');
        };
        push @items,$item
            if $item;
    }
 
    return $class->new({
        items => \@items,
    });
}
 
sub fetch {
    my ($class,$storage,$crypto) = @_;
 
    my $path = $class->items_path;
    my $data = $storage->get_item($path);
 
    return $class->from_json(
        $data,
        $crypto,
    );
}
 
1;