| 1 | package WebService::CloudFlare::Host::Role::Response; | ||
| 2 | use Moose::Role; | ||
| 3 | use JSON; | ||
| 4 | use Data::Dumper; | ||
| 5 | use Moose::Util::TypeConstraints; | ||
| 6 | |||
| 7 | requires 'res_map'; | ||
| 8 | |||
| 9 | sub BUILDARGS { | ||
| 10 | my ( $class, $http ) = @_; | ||
| 11 | |||
| 12 | die "HTTP Status " . $http->code . " returned, expected 200." | ||
| 13 | unless $http->code == 200; | ||
| 14 | |||
| 15 | my $json = decode_json( $http->content ); | ||
| 16 | my %map = $class->res_map; | ||
| 17 | my $args = { __JSON__ => $json }; | ||
| 18 | |||
| 19 | %map = __PACKAGE__->add_map_defaults( %map ); | ||
| 20 | |||
| 21 | OUTER: for my $key ( keys %map ) { | ||
| 22 | my ( @elems ) = split( ":", $map{$key} ); | ||
| 23 | my $tmp_json = $json; | ||
| 24 | for my $elem ( @elems ) { | ||
| 25 | next OUTER unless exists $tmp_json->{$elem}; | ||
| 26 | $tmp_json = $tmp_json->{$elem}; | ||
| 27 | } | ||
| 28 | $args->{$key} = $tmp_json; | ||
| 29 | #$self->$key($tmp_json); | ||
| 30 | } | ||
| 31 | return $args; | ||
| 32 | } | ||
| 33 | |||
| 34 | sub BUILD { | ||
| 35 | my ( $self ) = @_; | ||
| 36 | if ( $ENV{'CLOUDFLARE_TRACE'} ) { | ||
| 37 | print STDERR "<<< BEGIN CLOUDFLARE TRACE >>>\n"; | ||
| 38 | print STDERR "\t-> API Response ($self)\n"; | ||
| 39 | print STDERR Dumper $self->__JSON__; | ||
| 40 | print STDERR "<<< END CLOUDFLARE TRACE >>>\n"; | ||
| 41 | } | ||
| 42 | $self->unset_json; | ||
| 43 | } | ||
| 44 | |||
| 45 | # Oh, decode_json, how silly you can be. | ||
| 46 | subtype 'json_bool' => as 'Int'; | ||
| 47 | coerce 'json_bool', from 'Object', via { $_ ? 1 : 0 }; | ||
| 48 | |||
| 49 | has '__JSON__' => ( | ||
| 50 | is => 'ro', | ||
| 51 | required => 1, | ||
| 52 | clearer => 'unset_json' | ||
| 53 | ); | ||
| 54 | |||
| 55 | has [qw/ result action /] => ( is => 'rw', isa => 'Str', required => 1 ); | ||
| 56 | has [qw/ msg code /] => ( is => 'rw', isa => 'Str|Undef', required => 0 ); | ||
| 57 | |||
| 58 | sub add_map_defaults { | ||
| 59 | my ( $class, %map ) = @_; | ||
| 60 | |||
| 61 | $map{'msg'} = 'msg'; | ||
| 62 | $map{'action'} = 'request:act', | ||
| 63 | $map{'code'} = 'err_code', | ||
| 64 | $map{'result'} = 'result', | ||
| 65 | |||
| 66 | return %map; | ||
| 67 | } | ||
| 68 | |||
| 69 | 1; |