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. Using  Roles  to     Build  Web  Service  Clients  

    Mark  Allen   mrallen1@yahoo.com   @bytemeorg  
  2. 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/' }, );
  3. # 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"; } }
  4. 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); }
  5. 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); }
  6. THANK  YOU!   Slides:  h@ps://speakerdeck.com/mrallen1/   Email:  mrallen1  at  yahoo

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