Dancer-Plugin-RESTModel

 view release on metacpan or  search on metacpan

lib/Dancer/Plugin/RESTModel.pm  view on Meta::CPAN

package Dancer::Plugin::RESTModel;
use strict;
use warnings;

use Moose;
with 'Role::REST::Client';

use Dancer qw( :syntax :moose );
use Dancer::Plugin;
use Carp 'croak';

our $VERSION = 0.02;

my $schemas = {};

register model => sub {
  my (undef, $name) = plugin_args(@_);
  return $schemas->{$name} if exists $schemas->{$name};

  my $conf = plugin_setting;
  my $options = $conf->{$name}
    or croak "The schema '$name' is not configured";

  my $model = __PACKAGE__->new( %{$conf->{$name}} );
  $schemas->{$name} = $model;

  return $model;
};

__PACKAGE__->meta->make_immutable;

register_plugin;
42;
__END__

=head1 NAME

Dancer::Plugin::RESTModel - REST model class for Dancer apps


=head1 SYNOPSIS

set the REST endpoint in your Dancer configuration file:

    plugins:
      RESTModel:
        MyData:
          server: http://localhost:5000
          type: application/json
          clientattrs:
            timeout: 5

then use it from any of your routes/controllers:

    use Dancer ':syntax';
    use Dancer::Plugin::RESTModel;

    get '/' => sub {
        my $res = model('MyData')->post( 'foo/bar/baz', { meep => 'moop' } );

        my $code = $res->code; # e.g. 200 
        my $data = $res->data;

        ...
    };


=head1 DESCRIPTION

This plugin lets you talk to a REST server as a separate model from within
your Dancer app. It is useful for keeping your API decoupled from your app
while still being able to manage it through the configuration file.

It is a thin wrapper over L<Role::REST::Client>.

=head1 INTERFACE 

=head2 model()

The exported C<model()> function returns a REST Model object which provides
the standard HTTP 1.1 verbs as methods:

    post
    get
    put
    delete
    options
    head

All methods take these parameters:

=over 4

=item * url - the REST service being accessed

=item * data - The data structure to send (hashref, arrayref). The data will
be encoded according to the value of the I<type> attribute

=item * args - B<optional> hashref with arguments to augment the way the call
is handled. It currently provides the 'deserializer' key to change the
deserializer if you I<know> that the response's content-type is incorrect,
and also the 'preserve_headers' which, if set to true, will keep the headers
between calls:



( run in 2.136 seconds using v1.01-cache-2.11-cpan-cdf2f3d4e48 )