1 package Catalyst::Controller::DBIC::API;
3 #ABSTRACT: Provides a DBIx::Class web service automagically
5 BEGIN { extends 'Catalyst::Controller'; }
8 use DBIx::Class::ResultClass::HashRefInflator;
10 use Test::Deep::NoTest('eq_deeply');
11 use MooseX::Types::Moose(':all');
13 use Scalar::Util( 'blessed', 'reftype' );
15 use Catalyst::Controller::DBIC::API::Request;
16 use namespace::autoclean;
26 # no ->utf8 here because the request params get decoded by Catalyst
30 with 'Catalyst::Controller::DBIC::API::StoredResultSource',
31 'Catalyst::Controller::DBIC::API::StaticArguments';
33 with 'Catalyst::Controller::DBIC::API::RequestArguments' => { static => 1 };
35 __PACKAGE__->config();
39 package MyApp::Controller::API::RPC::Artist;
41 BEGIN { extends 'Catalyst::Controller::DBIC::API::RPC' }
44 ( # define parent chain action and PathPart
47 Chained => '/api/rpc/rpc_base',
51 class => 'MyAppDB::Artist',
52 resultset_class => 'MyAppDB::ResultSet::Artist',
53 create_requires => ['name', 'age'],
54 create_allows => ['nickname'],
55 update_allows => ['name', 'age', 'nickname'],
56 update_allows => ['name', 'age', 'nickname'],
57 select => ['name', 'age'],
62 { cds => ['tracks'] },
64 ordered_by => ['age'],
65 search_exposes => ['age', 'nickname', { cds => ['title', 'year'] }],
67 use_json_boolean => 1,
71 # Provides the following functional endpoints:
72 # /api/rpc/artist/create
73 # /api/rpc/artist/list
74 # /api/rpc/artist/id/[id]/delete
75 # /api/rpc/artist/id/[id]/update
82 begin is provided in the base class to setup the Catalyst request object by
83 applying the DBIC::API::Request role.
88 my ( $self, $c ) = @_;
90 Moose::Util::ensure_all_roles( $c->req,
91 'Catalyst::Controller::DBIC::API::Request' );
94 =method_protected setup
96 :Chained('specify.in.subclass.config') :CaptureArgs(0) :PathPart('specify.in.subclass.config')
98 This action is the chain root of the controller. It must either be overridden or
99 configured to provide a base PathPart to the action and also a parent action.
100 For example, for class MyAppDB::Track you might have
102 package MyApp::Controller::API::RPC::Track;
104 BEGIN { extends 'Catalyst::Controller::DBIC::API::RPC'; }
107 ( action => { setup => { PathPart => 'track', Chained => '/api/rpc/rpc_base' } },
113 sub setup :Chained('/api/rpc/rpc_base') :CaptureArgs(0) :PathPart('track') {
116 $self->next::method($c);
119 This action does nothing by default.
123 sub setup : Chained('specify.in.subclass.config') : CaptureArgs(0) :
124 PathPart('specify.in.subclass.config') { }
126 =method_protected deserialize
128 :Chained('setup') :CaptureArgs(0) :PathPart('') :ActionClass('Deserialize')
130 Absorbs the request data and transforms it into useful bits by using
131 CGI::Expand->expand_hash and a smattering of JSON->decode for a handful of
134 Current only the following arguments are capable of being expressed as JSON:
143 It should be noted that arguments can used mixed modes in with some caveats.
144 Each top level arg can be expressed as CGI::Expand with their immediate child
145 keys expressed as JSON when sending the data application/x-www-form-urlencoded.
146 Otherwise, you can send content as raw json and it will be deserialized as is
147 with no CGI::Expand expasion.
151 sub deserialize : Chained('setup') : CaptureArgs(0) : PathPart('') :
152 ActionClass('Deserialize') {
153 my ( $self, $c ) = @_;
156 if ( $c->req->data && scalar( keys %{ $c->req->data } ) ) {
157 $req_params = $c->req->data;
160 $req_params = CGI::Expand->expand_hash( $c->req->params );
163 @{ [ $self->search_arg, $self->count_arg,
164 $self->page_arg, $self->offset_arg,
165 $self->ordered_by_arg, $self->grouped_by_arg,
171 # these params can also be composed of JSON
172 # but skip if the parameter is not provided
173 next if not exists $req_params->{$param};
175 # find out if CGI::Expand was involved
176 if ( ref $req_params->{$param} eq 'HASH' ) {
177 for my $key ( keys %{ $req_params->{$param} } ) {
179 # copy the value because JSON::XS will alter it
180 # even if decoding failed
181 my $value = $req_params->{$param}->{$key};
183 my $deserialized = $self->_json->decode($value);
184 $req_params->{$param}->{$key} = $deserialized;
188 "Param '$param.$key' did not deserialize appropriately: $_"
195 my $value = $req_params->{$param};
196 my $deserialized = $self->_json->decode($value);
197 $req_params->{$param} = $deserialized;
201 "Param '$param' did not deserialize appropriately: $_"
208 $self->inflate_request( $c, $req_params );
211 =method_protected generate_rs
213 generate_rs is used by inflate_request to get a resultset for the current
214 request. It receives $c as its only argument.
215 By default it returns a resultset of the controller's class.
216 Override this method if you need to manipulate the default implementation of
222 my ( $self, $c ) = @_;
224 return $c->model( $c->stash->{class} || $self->class );
227 =method_protected inflate_request
229 inflate_request is called at the end of deserialize to populate key portions of
230 the request with the useful bits.
234 sub inflate_request {
235 my ( $self, $c, $params ) = @_;
238 # set static arguments
239 $c->req->_set_controller($self);
241 # set request arguments
242 $c->req->_set_request_data($params);
244 # set the current resultset
245 $c->req->_set_current_result_set( $self->generate_rs($c) );
250 $self->push_error( $c, { message => $_ } );
255 =method_protected object_with_id
257 :Chained('deserialize') :CaptureArgs(1) :PathPart('')
259 This action is the chain root for all object level actions (such as delete and
260 update) that operate on a single identifer. The provided identifier will be used
261 to find that particular object and add it to the request's store ofobjects.
263 Please see L<Catalyst::Controller::DBIC::API::Context> for more details on the
268 sub object_with_id : Chained('deserialize') : CaptureArgs(1) : PathPart('') {
269 my ( $self, $c, $id ) = @_;
271 my $vals = $c->req->request_data->{ $self->data_root };
272 unless ( defined($vals) ) {
274 # no data root, assume the request_data itself is the payload
275 $vals = $c->req->request_data;
279 # there can be only one set of data
280 $c->req->add_object( [ $self->object_lookup( $c, $id ), $vals ] );
284 $self->push_error( $c, { message => $_ } );
289 =method_protected objects_no_id
291 :Chained('deserialize') :CaptureArgs(0) :PathPart('')
293 This action is the chain root for object level actions (such as create, update,
294 or delete) that can involve more than one object. The data stored at the
295 data_root of the request_data will be interpreted as an array of hashes on which
296 to operate. If the hashes are missing an 'id' key, they will be considered a
297 new object to be created. Otherwise, the values in the hash will be used to
298 perform an update. As a special case, a single hash sent will be coerced into
301 Please see L<Catalyst::Controller::DBIC::API::Context> for more details on the
306 sub objects_no_id : Chained('deserialize') : CaptureArgs(0) : PathPart('') {
307 my ( $self, $c ) = @_;
309 if ( $c->req->has_request_data ) {
310 my $data = $c->req->request_data;
313 if ( exists( $data->{ $self->data_root } )
314 && defined( $data->{ $self->data_root } ) )
316 my $root = $data->{ $self->data_root };
317 if ( reftype($root) eq 'ARRAY' ) {
320 elsif ( reftype($root) eq 'HASH' ) {
324 $c->log->error('Invalid request data');
325 $self->push_error( $c,
326 { message => 'Invalid request data' } );
331 # no data root, assume the request_data itself is the payload
332 $vals = [ $c->req->request_data ];
335 foreach my $val (@$vals) {
336 unless ( exists( $val->{id} ) ) {
338 [ $c->req->current_result_set->new_result( {} ), $val ] );
344 [ $self->object_lookup( $c, $val->{id} ), $val ] );
348 $self->push_error( $c, { message => $_ } );
355 =method_protected object_lookup
357 This method provides the look up functionality for an object based on 'id'.
358 It is passed the current $c and the id to be used to perform the lookup.
359 Dies if there is no provided id or if no object was found.
364 my ( $self, $c, $id ) = @_;
366 die 'No valid ID provided for look up' unless defined $id and length $id;
367 my $object = $c->req->current_result_set->find($id);
368 die "No object found for id '$id'" unless defined $object;
372 =method_protected list
374 list's steps are broken up into three distinct methods:
378 =item L</list_munge_parameters>
380 =item L</list_perform_search>
382 =item L</list_format_output>.
386 The goal of this method is to call ->search() on the current_result_set,
387 change the resultset class of the result (if needed), and return it in
388 $c->stash->{$self->stash_key}->{$self->data_root}.
390 Please see the individual methods for more details on what actual processing
393 If the L</select> config param is defined then the hashes will contain only
394 those columns, otherwise all columns in the object will be returned.
395 L</select> of course supports the function/procedure calling semantics that
396 L<DBIx::Class::ResultSet/select> supports.
398 In order to have proper column names in the result, provide arguments in L</as>
399 (which also follows L<DBIx::Class::ResultSet/as> semantics.
400 Similarly L</count>, L</page>, L</grouped_by> and L</ordered_by> affect the
401 maximum number of rows returned as well as the ordering and grouping.
403 Note that if select, count, ordered_by or grouped_by request parameters are
404 present, these will override the values set on the class with select becoming
405 bound by the select_exposes attribute.
407 If not all objects in the resultset are required then it's possible to pass
408 conditions to the method as request parameters. You can use a JSON string as
409 the 'search' parameter for maximum flexibility or use L<CGI::Expand> syntax.
410 In the second case the request parameters are expanded into a structure and
411 then used as the search condition.
413 For example, these request parameters:
415 ?search.name=fred&search.cd.artist=luke
417 ?search={"name":"fred","cd": {"artist":"luke"}}
419 Would result in this search (where 'name' is a column of the result class, 'cd'
420 is a relation of the result class and 'artist' is a column of the related class):
422 $rs->search({ name => 'fred', 'cd.artist' => 'luke' }, { join => ['cd'] })
424 It is also possible to use a JSON string for expandeded parameters:
426 ?search.datetime={"-between":["2010-01-06 19:28:00","2010-01-07 19:28:00"]}
428 Note that if pagination is needed, this can be achieved using a combination of
429 the L</count> and L</page> parameters. For example:
433 Would result in this search:
435 $rs->search({}, { page => 2, rows => 20 })
440 my ( $self, $c ) = @_;
442 $self->list_munge_parameters($c);
443 $self->list_perform_search($c);
444 $self->list_format_output($c);
446 # make sure there are no objects lingering
447 $c->req->clear_objects();
450 =method_protected list_munge_parameters
452 list_munge_parameters is a noop by default. All arguments will be passed through
453 without any manipulation. In order to successfully manipulate the parameters
454 before the search is performed, simply access
455 $c->req->search_parameters|search_attributes (ArrayRef and HashRef respectively),
456 which correspond directly to ->search($parameters, $attributes).
457 Parameter keys will be in already-aliased form.
458 To store the munged parameters call $c->req->_set_search_parameters($newparams)
459 and $c->req->_set_search_attributes($newattrs).
463 sub list_munge_parameters { } # noop by default
465 =method_protected list_perform_search
467 list_perform_search executes the actual search. current_result_set is updated to
468 contain the result returned from ->search. If paging was requested,
469 search_total_entries will be set as well.
473 sub list_perform_search {
474 my ( $self, $c ) = @_;
480 $req->current_result_set->search( $req->search_parameters,
481 $req->search_attributes );
483 $req->_set_current_result_set($rs);
485 $req->_set_search_total_entries(
486 $req->current_result_set->pager->total_entries )
487 if $req->has_search_attributes
488 && ( exists( $req->search_attributes->{page} )
489 && defined( $req->search_attributes->{page} )
490 && length( $req->search_attributes->{page} ) );
494 $self->push_error( $c,
495 { message => 'a database error has occured.' } );
500 =method_protected list_format_output
502 list_format_output prepares the response for transmission across the wire.
503 A copy of the current_result_set is taken and its result_class is set to
504 L<DBIx::Class::ResultClass::HashRefInflator>. Each row in the resultset is then
505 iterated and passed to L</row_format_output> with the result of that call added
510 sub list_format_output {
511 my ( $self, $c ) = @_;
513 my $rs = $c->req->current_result_set->search;
514 $rs->result_class( $self->result_class ) if $self->result_class;
520 foreach my $row ( $rs->all ) {
521 push( @$formatted, $self->row_format_output( $c, $row ) );
524 $output->{ $self->data_root } = $formatted;
526 if ( $c->req->has_search_total_entries ) {
527 $output->{ $self->total_entries_arg } =
528 $c->req->search_total_entries + 0;
531 $c->stash->{ $self->stash_key } = $output;
535 $self->push_error( $c,
536 { message => 'a database error has occured.' } );
541 =method_protected row_format_output
543 row_format_output is called each row of the inflated output generated from the
544 search. It receives two arguments, the catalyst context and the hashref that
545 represents the row. By default, this method is merely a passthrough.
549 sub row_format_output {
551 #my ($self, $c, $row) = @_;
552 my ( $self, undef, $row ) = @_;
553 return $row; # passthrough by default
556 =method_protected item
558 item will return a single object called by identifier in the uri. It will be
559 inflated via each_object_inflate.
564 my ( $self, $c ) = @_;
566 if ( $c->req->count_objects != 1 ) {
568 $self->push_error( $c,
569 { message => 'No objects on which to operate' } );
573 $c->stash->{ $self->stash_key }->{ $self->item_root } =
574 $self->each_object_inflate( $c, $c->req->get_object(0)->[0] );
578 =method_protected update_or_create
580 update_or_create is responsible for iterating any stored objects and performing
581 updates or creates. Each object is first validated to ensure it meets the
582 criteria specified in the L</create_requires> and L</create_allows> (or
583 L</update_allows>) parameters of the controller config. The objects are then
584 committed within a transaction via L</transact_objects> using a closure around
589 sub update_or_create {
590 my ( $self, $c ) = @_;
592 if ( $c->req->has_objects ) {
593 $self->validate_objects($c);
594 $self->transact_objects( $c, sub { $self->save_objects( $c, @_ ) } );
598 $self->push_error( $c,
599 { message => 'No objects on which to operate' } );
604 =method_protected transact_objects
606 transact_objects performs the actual commit to the database via $schema->txn_do.
607 This method accepts two arguments, the context and a coderef to be used within
608 the transaction. All of the stored objects are passed as an arrayref for the
609 only argument to the coderef.
613 sub transact_objects {
614 my ( $self, $c, $coderef ) = @_;
617 $self->stored_result_source->schema->txn_do( $coderef,
622 $self->push_error( $c,
623 { message => 'a database error has occured.' } );
628 =method_protected validate_objects
630 This is a shortcut method for performing validation on all of the stored objects
631 in the request. Each object's provided values (for create or update) are updated
632 to the allowed values permitted by the various config parameters.
636 sub validate_objects {
637 my ( $self, $c ) = @_;
640 foreach my $obj ( $c->req->all_objects ) {
641 $obj->[1] = $self->validate_object( $c, $obj );
646 $c->log->error($err);
647 $err =~ s/\s+at\s+.+\n$//g;
648 $self->push_error( $c, { message => $err } );
653 =method_protected validate_object
655 validate_object takes the context and the object as an argument. It then filters
656 the passed values in slot two of the tuple through the create|update_allows
657 configured. It then returns those filtered values. Values that are not allowed
658 are silently ignored. If there are no values for a particular key, no valid
659 values at all, or multiple of the same key, this method will die.
663 sub validate_object {
664 my ( $self, $c, $obj ) = @_;
665 my ( $object, $params ) = @$obj;
668 my %requires_map = map { $_ => 1 } @{
669 ( $object->in_storage )
671 : $c->stash->{create_requires} || $self->create_requires
674 my %allows_map = map { ( ref $_ ) ? %{$_} : ( $_ => 1 ) } (
676 @{ ( $object->in_storage )
677 ? ( $c->stash->{update_allows} || $self->update_allows )
678 : ( $c->stash->{create_allows} || $self->create_allows )
682 foreach my $key ( keys %allows_map ) {
684 # check value defined if key required
685 my $allowed_fields = $allows_map{$key};
687 if ( ref $allowed_fields ) {
688 my $related_source = $object->result_source->related_source($key);
689 my $related_params = $params->{$key};
690 my %allowed_related_map = map { $_ => 1 } @$allowed_fields;
691 my $allowed_related_cols =
692 ( $allowed_related_map{'*'} )
693 ? [ $related_source->columns ]
696 foreach my $related_col ( @{$allowed_related_cols} ) {
698 my $related_col_value =
699 $related_params->{$related_col}
703 $values{$key}{$related_col} = $related_col_value;
708 my $value = $params->{$key};
710 if ( $requires_map{$key} ) {
711 unless ( defined($value) ) {
713 # if not defined look for default
714 $value = $object->result_source->column_info($key)
716 unless ( defined $value ) {
717 die "No value supplied for ${key} and no default";
722 # check for multiple values
723 if ( ref($value) && !( reftype($value) eq reftype(JSON::true) ) )
725 require Data::Dumper;
727 "Multiple values for '${key}': ${\Data::Dumper::Dumper($value)}";
730 # check exists so we don't just end up with hash of undefs
731 # check defined to account for default values being used
732 $values{$key} = $value
733 if exists $params->{$key} || defined $value;
737 unless ( keys %values || !$object->in_storage ) {
738 die 'No valid keys passed';
744 =method_protected delete
746 delete operates on the stored objects in the request. It first transacts the
747 objects, deleting them in the database using L</transact_objects> and a closure
748 around L</delete_objects>, and then clears the request store of objects.
753 my ( $self, $c ) = @_;
755 if ( $c->req->has_objects ) {
756 $self->transact_objects( $c,
757 sub { $self->delete_objects( $c, @_ ) } );
758 $c->req->clear_objects;
762 $self->push_error( $c,
763 { message => 'No objects on which to operate' } );
768 =method_protected save_objects
770 This method is used by update_or_create to perform the actual database
771 manipulations. It iterates each object calling L</save_object>.
776 my ( $self, $c, $objects ) = @_;
778 foreach my $obj (@$objects) {
779 $self->save_object( $c, $obj );
783 =method_protected save_object
785 save_object first checks to see if the object is already in storage. If so, it
786 calls L</update_object_from_params> otherwise L</insert_object_from_params>.
791 my ( $self, $c, $obj ) = @_;
793 my ( $object, $params ) = @$obj;
795 if ( $object->in_storage ) {
796 $self->update_object_from_params( $c, $object, $params );
799 $self->insert_object_from_params( $c, $object, $params );
804 =method_protected update_object_from_params
806 update_object_from_params iterates through the params to see if any of them are
807 pertinent to relations. If so it calls L</update_object_relation> with the
808 object, and the relation parameters. Then it calls ->update on the object.
812 sub update_object_from_params {
813 my ( $self, $c, $object, $params ) = @_;
815 foreach my $key ( keys %$params ) {
816 my $value = $params->{$key};
817 if ( ref($value) && !( reftype($value) eq reftype(JSON::true) ) ) {
818 $self->update_object_relation( $c, $object,
819 delete $params->{$key}, $key );
823 elsif ( $object->can($key) ) {
824 $object->$key($value);
827 # accessor != colname
830 $object->result_source->column_info($key)->{accessor};
831 $object->$accessor($value);
838 =method_protected update_object_relation
840 update_object_relation finds the relation to the object, then calls ->update
841 with the specified parameters.
845 sub update_object_relation {
846 my ( $self, $c, $object, $related_params, $relation ) = @_;
847 my $row = $object->find_related( $relation, {}, {} );
850 foreach my $key ( keys %$related_params ) {
851 my $value = $related_params->{$key};
852 if ( ref($value) && !( reftype($value) eq reftype(JSON::true) ) )
854 $self->update_object_relation( $c, $row,
855 delete $related_params->{$key}, $key );
859 elsif ( $row->can($key) ) {
863 # accessor != colname
866 $row->result_source->column_info($key)->{accessor};
867 $row->$accessor($value);
873 $object->create_related( $relation, $related_params );
877 =method_protected insert_object_from_params
879 Sets the columns of the object, then calls ->insert.
883 sub insert_object_from_params {
885 #my ($self, $c, $object, $params) = @_;
886 my ( $self, undef, $object, $params ) = @_;
889 while ( my ( $key, $value ) = each %{$params} ) {
890 if ( ref($value) && !( reftype($value) eq reftype(JSON::true) ) ) {
891 $rels{$key} = $value;
895 elsif ( $object->can($key) ) {
896 $object->$key($value);
899 # accessor != colname
902 $object->result_source->column_info($key)->{accessor};
903 $object->$accessor($value);
909 while ( my ( $k, $v ) = each %rels ) {
910 $object->create_related( $k, $v );
914 =method_protected delete_objects
916 Iterates through each object calling L</delete_object>.
921 my ( $self, $c, $objects ) = @_;
923 map { $self->delete_object( $c, $_->[0] ) } @$objects;
926 =method_protected delete_object
928 Performs the actual ->delete on the object.
934 #my ($self, $c, $object) = @_;
935 my ( $self, undef, $object ) = @_;
940 =method_protected end
942 end performs the final manipulation of the response before it is serialized.
943 This includes setting the success of the request both at the HTTP layer and
944 JSON layer. If configured with return_object true, and there are stored objects
945 as the result of create or update, those will be inflated according to the
946 schema and get_inflated_columns
951 my ( $self, $c ) = @_;
953 # don't change the http status code if already set elsewhere
954 unless ( $c->res->status && $c->res->status != 200 ) {
955 if ( $self->has_errors($c) ) {
956 $c->res->status(400);
959 $c->res->status(200);
963 if ( $c->res->status == 200 ) {
964 $c->stash->{ $self->stash_key }->{success} =
965 $self->use_json_boolean ? JSON::true : 'true';
966 if ( $self->return_object && $c->req->has_objects ) {
967 my $returned_objects = [];
968 push( @$returned_objects, $self->each_object_inflate( $c, $_ ) )
969 for map { $_->[0] } $c->req->all_objects;
970 $c->stash->{ $self->stash_key }->{ $self->data_root } =
971 scalar(@$returned_objects) > 1
973 : $returned_objects->[0];
977 $c->stash->{ $self->stash_key }->{success} =
978 $self->use_json_boolean ? JSON::false : 'false';
979 $c->stash->{ $self->stash_key }->{messages} = $self->get_errors($c)
980 if $self->has_errors($c);
982 # don't return data for error responses
983 delete $c->stash->{ $self->stash_key }->{ $self->data_root };
986 $c->forward('serialize');
989 =method_protected each_object_inflate
991 each_object_inflate executes during L</end> and allows hooking into the process
992 of inflating the objects to return in the response. Receives, the context, and
993 the object as arguments.
995 This only executes if L</return_object> if set and if there are any objects to
1000 sub each_object_inflate {
1002 #my ($self, $c, $object) = @_;
1003 my ( $self, undef, $object ) = @_;
1005 return { $object->get_columns };
1008 =method_protected serialize
1010 multiple actions forward to serialize which uses Catalyst::Action::Serialize.
1014 # from Catalyst::Action::Serialize
1015 sub serialize : ActionClass('Serialize') { }
1017 =method_protected push_error
1019 Stores an error message into the stash to be later retrieved by L</end>.
1020 Accepts a Dict[message => Str] parameter that defines the error message.
1025 my ( $self, $c, $params ) = @_;
1026 die 'Catalyst app object missing'
1028 my $error = 'unknown error';
1029 if ( exists $params->{message} ) {
1030 $error = $params->{message};
1032 # remove newline from die "error message\n" which is required to not
1033 # have the filename and line number in the error text
1036 push( @{ $c->stash->{_dbic_crud_errors} }, $error );
1039 =method_protected get_errors
1041 Returns all of the errors stored in the stash.
1046 my ( $self, $c ) = @_;
1047 die 'Catalyst app object missing'
1049 return $c->stash->{_dbic_crud_errors};
1052 =method_protected has_errors
1054 Returns true if errors are stored in the stash.
1059 my ( $self, $c ) = @_;
1060 die 'Catalyst app object missing'
1062 return exists $c->stash->{_dbic_crud_errors};
1067 Easily provide common API endpoints based on your L<DBIx::Class> schema classes.
1068 Module provides both RPC and REST interfaces to base functionality.
1069 Uses L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize> to
1070 serialize response and/or deserialise request.
1074 This document describes base functionlity such as list, create, delete, update
1075 and the setting of config attributes. L<Catalyst::Controller::DBIC::API::RPC>
1076 and L<Catalyst::Controller::DBIC::API::REST> describe details of provided
1077 endpoints to those base methods.
1079 You will need to create a controller for each schema class you require API
1080 endpoints for. For example if your schema has Artist and Track, and you want to
1081 provide a RESTful interface to these, you should create
1082 MyApp::Controller::API::REST::Artist and MyApp::Controller::API::REST::Track
1083 which both subclass L<Catalyst::Controller::DBIC::API::REST>.
1084 Similarly if you wanted to provide an RPC style interface then subclass
1085 L<Catalyst::Controller::DBIC::API::RPC>. You then configure these individually
1086 as specified in L</CONFIGURATION>.
1088 Also note that the test suite of this module has an example application used to
1089 run tests against. It maybe helpful to look at that until a better tutorial is
1092 =head2 CONFIGURATION
1094 Each of your controller classes needs to be configured to point at the relevant
1095 schema class, specify what can be updated and so on, as shown in the L</SYNOPSIS>.
1097 The class, create_requires, create_allows and update_requires parameters can
1098 also be set in the stash like so:
1100 sub setup :Chained('/api/rpc/rpc_base') :CaptureArgs(1) :PathPart('any') {
1101 my ($self, $c, $object_type) = @_;
1103 if ($object_type eq 'artist') {
1104 $c->stash->{class} = 'MyAppDB::Artist';
1105 $c->stash->{create_requires} = [qw/name/];
1106 $c->stash->{update_allows} = [qw/name/];
1108 $self->push_error($c, { message => "invalid object_type" });
1112 $self->next::method($c);
1115 Generally it's better to have one controller for each DBIC source with the
1116 config hardcoded, but in some cases this isn't possible.
1118 Note that the Chained, CaptureArgs and PathPart are just standard Catalyst
1119 configuration parameters and that then endpoint specified in Chained - in this
1120 case '/api/rpc/rpc_base' - must actually exist elsewhere in your application.
1121 See L<Catalyst::DispatchType::Chained> for more details.
1123 Below are explanations for various configuration parameters. Please see
1124 L<Catalyst::Controller::DBIC::API::StaticArguments> for more details.
1128 Whatever you would pass to $c->model to get a resultset for this class.
1129 MyAppDB::Track for example.
1131 =head3 resultset_class
1133 Desired resultset class after accessing your model. MyAppDB::ResultSet::Track
1134 for example. By default, it's DBIx::Class::ResultClass::HashRefInflator.
1135 Set to empty string to leave resultset class without change.
1139 Controls where in stash request_data should be stored, and defaults to 'response'.
1143 By default, the response data is serialized into
1144 $c->stash->{$self->stash_key}->{$self->data_root} and data_root defaults to
1145 'list' to preserve backwards compatibility. This is now configuable to meet
1146 the needs of the consuming client.
1148 =head3 use_json_boolean
1150 By default, the response success status is set to a string value of "true" or
1151 "false". If this attribute is true, JSON's true() and false() will be used
1152 instead. Note, this does not effect other internal processing of boolean values.
1154 =head3 count_arg, page_arg, select_arg, search_arg, grouped_by_arg, ordered_by_arg, prefetch_arg, as_arg, total_entries_arg
1156 These attributes allow customization of the component to understand requests
1157 made by clients where these argument names are not flexible and cannot conform
1158 to this components defaults.
1160 =head3 create_requires
1162 Arrayref listing columns required to be passed to create in order for the
1163 request to be valid.
1165 =head3 create_allows
1167 Arrayref listing columns additional to those specified in create_requires that
1168 are not required to create but which create does allow. Columns passed to create
1169 that are not listed in create_allows or create_requires will be ignored.
1171 =head3 update_allows
1173 Arrayref listing columns that update will allow. Columns passed to update that
1174 are not listed here will be ignored.
1178 Arguments to pass to L<DBIx::Class::ResultSet/select> when performing search for
1183 Complements arguments passed to L<DBIx::Class::ResultSet/select> when performing
1184 a search. This allows you to specify column names in the result for RDBMS
1187 =head3 select_exposes
1189 Columns and related columns that are okay to return in the resultset since
1190 clients can request more or less information specified than the above select
1195 Arguments to pass to L<DBIx::Class::ResultSet/prefetch> when performing search
1198 =head3 prefetch_allows
1200 Arrayref listing relationships that are allowed to be prefetched.
1201 This is necessary to avoid denial of service attacks in form of
1202 queries which would return a large number of data
1203 and unwanted disclosure of data.
1207 Arguments to pass to L<DBIx::Class::ResultSet/group_by> when performing search
1212 Arguments to pass to L<DBIx::Class::ResultSet/order_by> when performing search
1215 =head3 search_exposes
1217 Columns and related columns that are okay to search on. For example if only the
1218 position column and all cd columns were to be allowed
1220 search_exposes => [qw/position/, { cd => ['*'] }]
1222 You can also use this to allow custom columns should you wish to allow them
1223 through in order to be caught by a custom resultset. For example:
1225 package RestTest::Controller::API::RPC::TrackExposed;
1231 search_exposes => [qw/position title custom_column/],
1234 and then in your custom resultset:
1236 package RestTest::Schema::ResultSet::Track;
1238 use base 'RestTest::Schema::ResultSet';
1242 my ($clause, $params) = @_;
1245 if (my $pretend = delete $clause->{custom_column}) {
1246 $clause->{'cd.year'} = $pretend;
1248 my $rs = $self->SUPER::search(@_);
1253 Arguments to pass to L<DBIx::Class::ResultSet/rows> when performing search for
1258 Arguments to pass to L<DBIx::Class::ResultSet/page> when performing search for
1263 By default the create, delete and update actions will not return anything apart
1264 from the success parameter set in L</end>, often this is not ideal but the
1265 required behaviour varies from application to application. So normally it's
1266 sensible to write an intermediate class which your main controller classes
1269 For example if you wanted create to return the JSON for the newly created
1270 object you might have something like:
1272 package MyApp::ControllerBase::DBIC::API::RPC;
1275 BEGIN { extends 'Catalyst::Controller::DBIC::API::RPC' };
1277 sub create :Chained('setup') :Args(0) :PathPart('create') {
1278 my ($self, $c) = @_;
1280 # $c->req->all_objects will contain all of the created
1281 $self->next::method($c);
1283 if ($c->req->has_objects) {
1284 # $c->stash->{$self->stash_key} will be serialized in the end action
1285 $c->stash->{$self->stash_key}->{$self->data_root} = [ map { { $_->get_inflated_columns } } ($c->req->all_objects) ] ;
1289 package MyApp::Controller::API::RPC::Track;
1292 BEGIN { extends 'MyApp::ControllerBase::DBIC::API::RPC' };
1295 It should be noted that the return_object attribute will produce the above
1296 result for you, free of charge.
1298 Similarly you might want create, update and delete to all forward to the list
1299 action once they are done so you can refresh your view. This should also be
1302 If more extensive customization is required, it is recommened to peer into the
1303 roles that comprise the system and make use
1307 It should be noted that version 1.004 and above makes a rapid depature from the
1308 status quo. The internals were revamped to use more modern tools such as Moose
1309 and its role system to refactor functionality out into self-contained roles.
1311 To this end, internally, this module now understands JSON boolean values (as
1312 represented by the JSON module) and will Do The Right Thing in handling those
1313 values. This means you can have ColumnInflators installed that can covert
1314 between JSON booleans and whatever your database wants for boolean values.
1316 Validation for various *_allows or *_exposes is now accomplished via
1317 Data::DPath::Validator with a lightly simplified, via a subclass of
1318 Data::DPath::Validator::Visitor.
1320 The rough jist of the process goes as follows: Arguments provided to those
1321 attributes are fed into the Validator and Data::DPaths are generated.
1322 Then incoming requests are validated against these paths generated.
1323 The validator is set in "loose" mode meaning only one path is required to match.
1324 For more information, please see L<Data::DPath::Validator> and more specifically
1325 L<Catalyst::Controller::DBIC::API::Validator>.
1328 Transactions are used. The stash is put aside in favor of roles applied to the
1329 request object with additional accessors.
1330 Error handling is now much more consistent with most errors immediately detaching.
1331 The internals are much easier to read and understand with lots more documentation.