Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Using Roles to Build Perl Web Service Clients

Using Roles to Build Perl Web Service Clients

Slides for a talk delivered at YAPC::NA 2014 in Orlando, FL

Jade Allen

June 24, 2014
Tweet

More Decks by Jade Allen

Other Decks in Technology

Transcript

  1. use strict; package WebService::Foobar::Request; use Moo::Role; use warnings NONFATAL =>

    'all'; use HTTP::Tiny; use Carp qw(confess); has 'ua' => ( is => 'ro', lazy => 1, default => sub { HTTP::Tiny->new( agent => 'WebService-Foobar ', default_headers => { 'Content-Type' => 'application/json' }, ) }, ); has 'base_url' => ( is => 'ro', lazy => 1, default => sub { 'http://api.foobar.io/v1/' }, );
  2. # package WebService::Foobar::Request; # ... sub _request { my ($self,

    $op, $data) = @_; # ideally $data is already serialized my $url = $self->_build_url($op) or confess "Couldn't build url for $op\n"; my $result = $self->ua->request('POST', $url, {content=>$data}); if ( $result->{success} ) return $result; } else { confess "Request to $url failed. Got (" . $result->{status} . ") " . $result->{content} . "\n"; } }
  3. use strict; package WebService::Foobar::JSON; use Moo::Role; use warnings NONFATAL =>

    'all'; use JSON; use Carp qw(confess); has 'serializer' => ( is => 'ro', lazy => 1, default => sub { JSON->new() }, ); sub encode { my ($self, $ref) = @_; $self->serializer->encode($ref); } sub decode { my ($self, $data) = @_; $self->serializer->decode($data); }
  4. use strict; package WebService::Foobar::Data; use Moo; use warnings NONFATAL =>

    'all'; use Storable qw(dcopy); with 'WebService::Foobar::JSON'; has 'bar' => ( 'is' => 'rw' ); has 'baz' => ( 'qux' => 'ro' ); sub qux { my $self = shift; print $self->bar . " and " . $self->baz; } sub _serialize { my $self = shift; my $copy = dcopy($self); $self->encode($copy); }
  5. THANK  YOU!   Slides:  h@ps://speakerdeck.com/mrallen1/   Email:  mrallen1  at  yahoo

     dot  com   Twi-er:  @bytemeorg   Github:  h@ps://github.com/mrallen1