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'] }],
68 use_json_boolean => 1,
72 # Provides the following functional endpoints:
73 # /api/rpc/artist/create
74 # /api/rpc/artist/list
75 # /api/rpc/artist/id/[id]/delete
76 # /api/rpc/artist/id/[id]/update
83 begin is provided in the base class to setup the Catalyst request object by
84 applying the DBIC::API::Request role.
89 my ( $self, $c ) = @_;
91 Moose::Util::ensure_all_roles( $c->req,
92 'Catalyst::Controller::DBIC::API::Request' );
95 =method_protected setup
97 :Chained('specify.in.subclass.config') :CaptureArgs(0) :PathPart('specify.in.subclass.config')
99 This action is the chain root of the controller. It must either be overridden or
100 configured to provide a base PathPart to the action and also a parent action.
101 For example, for class MyAppDB::Track you might have
103 package MyApp::Controller::API::RPC::Track;
105 BEGIN { extends 'Catalyst::Controller::DBIC::API::RPC'; }
108 ( action => { setup => { PathPart => 'track', Chained => '/api/rpc/rpc_base' } },
114 sub setup :Chained('/api/rpc/rpc_base') :CaptureArgs(0) :PathPart('track') {
117 $self->next::method($c);
120 This action does nothing by default.
124 sub setup : Chained('specify.in.subclass.config') : CaptureArgs(0) :
125 PathPart('specify.in.subclass.config') { }
127 =method_protected deserialize
129 :Chained('setup') :CaptureArgs(0) :PathPart('') :ActionClass('Deserialize')
131 Absorbs the request data and transforms it into useful bits by using
132 CGI::Expand->expand_hash and a smattering of JSON->decode for a handful of
135 Current only the following arguments are capable of being expressed as JSON:
144 It should be noted that arguments can used mixed modes in with some caveats.
145 Each top level arg can be expressed as CGI::Expand with their immediate child
146 keys expressed as JSON when sending the data application/x-www-form-urlencoded.
147 Otherwise, you can send content as raw json and it will be deserialized as is
148 with no CGI::Expand expasion.
152 sub deserialize : Chained('setup') : CaptureArgs(0) : PathPart('') :
153 ActionClass('Deserialize') {
154 my ( $self, $c ) = @_;
157 if ( $c->req->data && scalar( keys %{ $c->req->data } ) ) {
158 $req_params = $c->req->data;
161 $req_params = CGI::Expand->expand_hash( $c->req->params );
164 @{ [ $self->search_arg, $self->count_arg,
165 $self->page_arg, $self->offset_arg,
166 $self->ordered_by_arg, $self->grouped_by_arg,
172 # these params can also be composed of JSON
173 # but skip if the parameter is not provided
174 next if not exists $req_params->{$param};
176 # find out if CGI::Expand was involved
177 if ( ref $req_params->{$param} eq 'HASH' ) {
178 for my $key ( keys %{ $req_params->{$param} } ) {
180 # copy the value because JSON::XS will alter it
181 # even if decoding failed
182 my $value = $req_params->{$param}->{$key};
184 my $deserialized = $self->_json->decode($value);
185 $req_params->{$param}->{$key} = $deserialized;
189 "Param '$param.$key' did not deserialize appropriately: $_"
196 my $value = $req_params->{$param};
197 my $deserialized = $self->_json->decode($value);
198 $req_params->{$param} = $deserialized;
202 "Param '$param' did not deserialize appropriately: $_"
209 $self->inflate_request( $c, $req_params );
212 =method_protected generate_rs
214 generate_rs is used by inflate_request to get a resultset for the current
215 request. It receives $c as its only argument.
216 By default it returns a resultset of the controller's class.
217 Override this method if you need to manipulate the default implementation of
223 my ( $self, $c ) = @_;
225 return $c->model( $c->stash->{class} || $self->class );
228 =method_protected inflate_request
230 inflate_request is called at the end of deserialize to populate key portions of
231 the request with the useful bits.
235 sub inflate_request {
236 my ( $self, $c, $params ) = @_;
239 # set static arguments
240 $c->req->_set_controller($self);
242 # set request arguments
243 $c->req->_set_request_data($params);
245 # set the current resultset
246 $c->req->_set_current_result_set( $self->generate_rs($c) );
251 $self->push_error( $c, { message => $_ } );
256 =method_protected object_with_id
258 :Chained('deserialize') :CaptureArgs(1) :PathPart('')
260 This action is the chain root for all object level actions (such as delete and
261 update) that operate on a single identifer. The provided identifier will be used
262 to find that particular object and add it to the request's store ofobjects.
264 Please see L<Catalyst::Controller::DBIC::API::Request::Context> for more
265 details on the stored objects.
269 sub object_with_id : Chained('deserialize') : CaptureArgs(1) : PathPart('') {
270 my ( $self, $c, $id ) = @_;
272 my $vals = $c->req->request_data->{ $self->data_root };
273 unless ( defined($vals) ) {
275 # no data root, assume the request_data itself is the payload
276 $vals = $c->req->request_data;
280 # there can be only one set of data
281 $c->req->add_object( [ $self->object_lookup( $c, $id ), $vals ] );
285 $self->push_error( $c, { message => $_ } );
290 =method_protected objects_no_id
292 :Chained('deserialize') :CaptureArgs(0) :PathPart('')
294 This action is the chain root for object level actions (such as create, update,
295 or delete) that can involve more than one object. The data stored at the
296 data_root of the request_data will be interpreted as an array of hashes on which
297 to operate. If the hashes are missing an 'id' key, they will be considered a
298 new object to be created. Otherwise, the values in the hash will be used to
299 perform an update. As a special case, a single hash sent will be coerced into
302 Please see L<Catalyst::Controller::DBIC::API::Request::Context> for more
303 details on the stored objects.
307 sub objects_no_id : Chained('deserialize') : CaptureArgs(0) : PathPart('') {
308 my ( $self, $c ) = @_;
310 if ( $c->req->has_request_data ) {
311 my $data = $c->req->request_data;
314 if ( exists( $data->{ $self->data_root } )
315 && defined( $data->{ $self->data_root } ) )
317 my $root = $data->{ $self->data_root };
318 if ( reftype($root) eq 'ARRAY' ) {
321 elsif ( reftype($root) eq 'HASH' ) {
325 $c->log->error('Invalid request data');
326 $self->push_error( $c,
327 { message => 'Invalid request data' } );
332 # no data root, assume the request_data itself is the payload
333 $vals = [ $c->req->request_data ];
336 foreach my $val (@$vals) {
337 unless ( exists( $val->{id} ) ) {
339 [ $c->req->current_result_set->new_result( {} ), $val ] );
345 [ $self->object_lookup( $c, $val->{id} ), $val ] );
349 $self->push_error( $c, { message => $_ } );
356 =method_protected object_lookup
358 This method provides the look up functionality for an object based on 'id'.
359 It is passed the current $c and the id to be used to perform the lookup.
360 Dies if there is no provided id or if no object was found.
365 my ( $self, $c, $id ) = @_;
367 die 'No valid ID provided for look up' unless defined $id and length $id;
368 my $object = $c->req->current_result_set->find($id);
369 die "No object found for id '$id'" unless defined $object;
373 =method_protected list
375 list's steps are broken up into three distinct methods:
379 =item L</list_munge_parameters>
381 =item L</list_perform_search>
383 =item L</list_format_output>.
387 The goal of this method is to call ->search() on the current_result_set,
388 change the resultset class of the result (if needed), and return it in
389 $c->stash->{$self->stash_key}->{$self->data_root}.
391 Please see the individual methods for more details on what actual processing
394 If the L</select> config param is defined then the hashes will contain only
395 those columns, otherwise all columns in the object will be returned.
396 L</select> of course supports the function/procedure calling semantics that
397 L<DBIx::Class::ResultSet/select> supports.
399 In order to have proper column names in the result, provide arguments in L</as>
400 (which also follows L<DBIx::Class::ResultSet/as> semantics.
401 Similarly L</count>, L</page>, L</grouped_by> and L</ordered_by> affect the
402 maximum number of rows returned as well as the ordering and grouping.
404 Note that if select, count, ordered_by or grouped_by request parameters are
405 present, these will override the values set on the class with select becoming
406 bound by the select_exposes attribute.
408 If not all objects in the resultset are required then it's possible to pass
409 conditions to the method as request parameters. You can use a JSON string as
410 the 'search' parameter for maximum flexibility or use L<CGI::Expand> syntax.
411 In the second case the request parameters are expanded into a structure and
412 then used as the search condition.
414 For example, these request parameters:
416 ?search.name=fred&search.cd.artist=luke
418 ?search={"name":"fred","cd": {"artist":"luke"}}
420 Would result in this search (where 'name' is a column of the result class, 'cd'
421 is a relation of the result class and 'artist' is a column of the related class):
423 $rs->search({ name => 'fred', 'cd.artist' => 'luke' }, { join => ['cd'] })
425 It is also possible to use a JSON string for expandeded parameters:
427 ?search.datetime={"-between":["2010-01-06 19:28:00","2010-01-07 19:28:00"]}
429 Note that if pagination is needed, this can be achieved using a combination of
430 the L</count> and L</page> parameters. For example:
434 Would result in this search:
436 $rs->search({}, { page => 2, rows => 20 })
441 my ( $self, $c ) = @_;
443 $self->list_munge_parameters($c);
444 $self->list_perform_search($c);
445 $self->list_format_output($c);
447 # make sure there are no objects lingering
448 $c->req->clear_objects();
451 =method_protected list_munge_parameters
453 list_munge_parameters is a noop by default. All arguments will be passed through
454 without any manipulation. In order to successfully manipulate the parameters
455 before the search is performed, simply access
456 $c->req->search_parameters|search_attributes (ArrayRef and HashRef respectively),
457 which correspond directly to ->search($parameters, $attributes).
458 Parameter keys will be in already-aliased form.
459 To store the munged parameters call $c->req->_set_search_parameters($newparams)
460 and $c->req->_set_search_attributes($newattrs).
464 sub list_munge_parameters { } # noop by default
466 =method_protected list_perform_search
468 list_perform_search executes the actual search. current_result_set is updated to
469 contain the result returned from ->search. If paging was requested,
470 search_total_entries will be set as well.
474 sub list_perform_search {
475 my ( $self, $c ) = @_;
481 $req->current_result_set->search( $req->search_parameters,
482 $req->search_attributes );
484 $req->_set_current_result_set($rs);
486 $req->_set_search_total_entries(
487 $req->current_result_set->pager->total_entries )
488 if $req->has_search_attributes
489 && ( exists( $req->search_attributes->{page} )
490 && defined( $req->search_attributes->{page} )
491 && length( $req->search_attributes->{page} ) );
495 $self->push_error( $c,
496 { message => 'a database error has occured.' } );
501 =method_protected list_format_output
503 list_format_output prepares the response for transmission across the wire.
504 A copy of the current_result_set is taken and its result_class is set to
505 L<DBIx::Class::ResultClass::HashRefInflator>. Each row in the resultset is then
506 iterated and passed to L</row_format_output> with the result of that call added
511 sub list_format_output {
512 my ( $self, $c ) = @_;
514 my $rs = $c->req->current_result_set->search;
515 $rs->result_class( $self->result_class ) if $self->result_class;
521 foreach my $row ( $rs->all ) {
522 push( @$formatted, $self->row_format_output( $c, $row ) );
525 $output->{ $self->data_root } = $formatted;
527 if ( $c->req->has_search_total_entries ) {
528 $output->{ $self->total_entries_arg } =
529 $c->req->search_total_entries + 0;
532 $c->stash->{ $self->stash_key } = $output;
536 $self->push_error( $c,
537 { message => 'a database error has occured.' } );
542 =method_protected row_format_output
544 row_format_output is called each row of the inflated output generated from the
545 search. It receives two arguments, the catalyst context and the hashref that
546 represents the row. By default, this method is merely a passthrough.
550 sub row_format_output {
552 #my ($self, $c, $row) = @_;
553 my ( $self, undef, $row ) = @_;
554 return $row; # passthrough by default
557 =method_protected item
559 item will return a single object called by identifier in the uri. It will be
560 inflated via each_object_inflate.
565 my ( $self, $c ) = @_;
567 if ( $c->req->count_objects != 1 ) {
569 $self->push_error( $c,
570 { message => 'No objects on which to operate' } );
574 $c->stash->{ $self->stash_key }->{ $self->item_root } =
575 $self->each_object_inflate( $c, $c->req->get_object(0)->[0] );
579 =method_protected update_or_create
581 update_or_create is responsible for iterating any stored objects and performing
582 updates or creates. Each object is first validated to ensure it meets the
583 criteria specified in the L</create_requires> and L</create_allows> (or
584 L</update_allows>) parameters of the controller config. The objects are then
585 committed within a transaction via L</transact_objects> using a closure around
590 sub update_or_create {
591 my ( $self, $c ) = @_;
593 if ( $c->req->has_objects ) {
594 $self->validate_objects($c);
595 $self->transact_objects( $c, sub { $self->save_objects( $c, @_ ) } );
599 $self->push_error( $c,
600 { message => 'No objects on which to operate' } );
605 =method_protected transact_objects
607 transact_objects performs the actual commit to the database via $schema->txn_do.
608 This method accepts two arguments, the context and a coderef to be used within
609 the transaction. All of the stored objects are passed as an arrayref for the
610 only argument to the coderef.
614 sub transact_objects {
615 my ( $self, $c, $coderef ) = @_;
618 $self->stored_result_source->schema->txn_do( $coderef,
623 $self->push_error( $c,
624 { message => 'a database error has occured.' } );
629 =method_protected validate_objects
631 This is a shortcut method for performing validation on all of the stored objects
632 in the request. Each object's provided values (for create or update) are updated
633 to the allowed values permitted by the various config parameters.
637 sub validate_objects {
638 my ( $self, $c ) = @_;
641 foreach my $obj ( $c->req->all_objects ) {
642 $obj->[1] = $self->validate_object( $c, $obj );
647 $c->log->error($err);
648 $err =~ s/\s+at\s+.+\n$//g;
649 $self->push_error( $c, { message => $err } );
654 =method_protected validate_object
656 validate_object takes the context and the object as an argument. It then filters
657 the passed values in slot two of the tuple through the create|update_allows
658 configured. It then returns those filtered values. Values that are not allowed
659 are silently ignored. If there are no values for a particular key, no valid
660 values at all, or multiple of the same key, this method will die.
664 sub validate_object {
665 my ( $self, $c, $obj ) = @_;
666 my ( $object, $params ) = @$obj;
669 my %requires_map = map { $_ => 1 } @{
670 ( $object->in_storage )
672 : $c->stash->{create_requires} || $self->create_requires
675 my %allows_map = map { ( ref $_ ) ? %{$_} : ( $_ => 1 ) } (
677 @{ ( $object->in_storage )
678 ? ( $c->stash->{update_allows} || $self->update_allows )
679 : ( $c->stash->{create_allows} || $self->create_allows )
683 foreach my $key ( keys %allows_map ) {
685 # check value defined if key required
686 my $allowed_fields = $allows_map{$key};
688 if ( ref $allowed_fields ) {
689 my $related_source = $object->result_source->related_source($key);
690 my $related_params = $params->{$key};
691 my %allowed_related_map = map { $_ => 1 } @$allowed_fields;
692 my $allowed_related_cols =
693 ( $allowed_related_map{'*'} )
694 ? [ $related_source->columns ]
697 foreach my $related_col ( @{$allowed_related_cols} ) {
699 my $related_col_value =
700 $related_params->{$related_col}
704 $values{$key}{$related_col} = $related_col_value;
709 my $value = $params->{$key};
711 if ( $requires_map{$key} ) {
712 unless ( defined($value) ) {
714 # if not defined look for default
715 $value = $object->result_source->column_info($key)
717 unless ( defined $value ) {
718 die "No value supplied for ${key} and no default";
723 # check for multiple values
724 if ( ref($value) && !( reftype($value) eq reftype(JSON::true) ) )
726 require Data::Dumper;
728 "Multiple values for '${key}': ${\Data::Dumper::Dumper($value)}";
731 # check exists so we don't just end up with hash of undefs
732 # check defined to account for default values being used
733 $values{$key} = $value
734 if exists $params->{$key} || defined $value;
738 unless ( keys %values || !$object->in_storage ) {
739 die 'No valid keys passed';
745 =method_protected delete
747 delete operates on the stored objects in the request. It first transacts the
748 objects, deleting them in the database using L</transact_objects> and a closure
749 around L</delete_objects>, and then clears the request store of objects.
754 my ( $self, $c ) = @_;
756 if ( $c->req->has_objects ) {
757 $self->transact_objects( $c,
758 sub { $self->delete_objects( $c, @_ ) } );
759 $c->req->clear_objects;
763 $self->push_error( $c,
764 { message => 'No objects on which to operate' } );
769 =method_protected save_objects
771 This method is used by update_or_create to perform the actual database
772 manipulations. It iterates each object calling L</save_object>.
777 my ( $self, $c, $objects ) = @_;
779 foreach my $obj (@$objects) {
780 $self->save_object( $c, $obj );
784 =method_protected save_object
786 save_object first checks to see if the object is already in storage. If so, it
787 calls L</update_object_from_params> otherwise L</insert_object_from_params>.
792 my ( $self, $c, $obj ) = @_;
794 my ( $object, $params ) = @$obj;
796 if ( $object->in_storage ) {
797 $self->update_object_from_params( $c, $object, $params );
800 $self->insert_object_from_params( $c, $object, $params );
805 =method_protected update_object_from_params
807 update_object_from_params iterates through the params to see if any of them are
808 pertinent to relations. If so it calls L</update_object_relation> with the
809 object, and the relation parameters. Then it calls ->update on the object.
813 sub update_object_from_params {
814 my ( $self, $c, $object, $params ) = @_;
816 foreach my $key ( keys %$params ) {
817 my $value = $params->{$key};
818 if ( ref($value) && !( reftype($value) eq reftype(JSON::true) ) ) {
819 $self->update_object_relation( $c, $object,
820 delete $params->{$key}, $key );
824 elsif ( $object->can($key) ) {
825 $object->$key($value);
828 # accessor != colname
831 $object->result_source->column_info($key)->{accessor};
832 $object->$accessor($value);
839 =method_protected update_object_relation
841 update_object_relation finds the relation to the object, then calls ->update
842 with the specified parameters.
846 sub update_object_relation {
847 my ( $self, $c, $object, $related_params, $relation ) = @_;
848 my $row = $object->find_related( $relation, {}, {} );
851 foreach my $key ( keys %$related_params ) {
852 my $value = $related_params->{$key};
853 if ( ref($value) && !( reftype($value) eq reftype(JSON::true) ) )
855 $self->update_object_relation( $c, $row,
856 delete $related_params->{$key}, $key );
860 elsif ( $row->can($key) ) {
864 # accessor != colname
867 $row->result_source->column_info($key)->{accessor};
868 $row->$accessor($value);
874 $object->create_related( $relation, $related_params );
878 =method_protected insert_object_from_params
880 Sets the columns of the object, then calls ->insert.
884 sub insert_object_from_params {
886 #my ($self, $c, $object, $params) = @_;
887 my ( $self, undef, $object, $params ) = @_;
890 while ( my ( $key, $value ) = each %{$params} ) {
891 if ( ref($value) && !( reftype($value) eq reftype(JSON::true) ) ) {
892 $rels{$key} = $value;
896 elsif ( $object->can($key) ) {
897 $object->$key($value);
900 # accessor != colname
903 $object->result_source->column_info($key)->{accessor};
904 $object->$accessor($value);
910 while ( my ( $k, $v ) = each %rels ) {
911 $object->create_related( $k, $v );
915 =method_protected delete_objects
917 Iterates through each object calling L</delete_object>.
922 my ( $self, $c, $objects ) = @_;
924 map { $self->delete_object( $c, $_->[0] ) } @$objects;
927 =method_protected delete_object
929 Performs the actual ->delete on the object.
935 #my ($self, $c, $object) = @_;
936 my ( $self, undef, $object ) = @_;
941 =method_protected end
943 end performs the final manipulation of the response before it is serialized.
944 This includes setting the success of the request both at the HTTP layer and
945 JSON layer. If configured with return_object true, and there are stored objects
946 as the result of create or update, those will be inflated according to the
947 schema and get_inflated_columns
952 my ( $self, $c ) = @_;
954 # don't change the http status code if already set elsewhere
955 unless ( $c->res->status && $c->res->status != 200 ) {
956 if ( $self->has_errors($c) ) {
957 $c->res->status(400);
960 $c->res->status(200);
964 if ( $c->res->status == 200 ) {
965 $c->stash->{ $self->stash_key }->{success} =
966 $self->use_json_boolean ? JSON::true : 'true';
967 if ( $self->return_object && $c->req->has_objects ) {
968 my $returned_objects = [];
969 push( @$returned_objects, $self->each_object_inflate( $c, $_ ) )
970 for map { $_->[0] } $c->req->all_objects;
971 $c->stash->{ $self->stash_key }->{ $self->data_root } =
972 scalar(@$returned_objects) > 1
974 : $returned_objects->[0];
978 $c->stash->{ $self->stash_key }->{success} =
979 $self->use_json_boolean ? JSON::false : 'false';
980 $c->stash->{ $self->stash_key }->{messages} = $self->get_errors($c)
981 if $self->has_errors($c);
983 # don't return data for error responses
984 delete $c->stash->{ $self->stash_key }->{ $self->data_root };
987 $c->forward('serialize');
990 =method_protected each_object_inflate
992 each_object_inflate executes during L</end> and allows hooking into the process
993 of inflating the objects to return in the response. Receives, the context, and
994 the object as arguments.
996 This only executes if L</return_object> if set and if there are any objects to
1001 sub each_object_inflate {
1003 #my ($self, $c, $object) = @_;
1004 my ( $self, undef, $object ) = @_;
1006 return { $object->get_columns };
1009 =method_protected serialize
1011 multiple actions forward to serialize which uses Catalyst::Action::Serialize.
1015 # from Catalyst::Action::Serialize
1016 sub serialize : ActionClass('Serialize') { }
1018 =method_protected push_error
1020 Stores an error message into the stash to be later retrieved by L</end>.
1021 Accepts a Dict[message => Str] parameter that defines the error message.
1026 my ( $self, $c, $params ) = @_;
1027 die 'Catalyst app object missing'
1029 my $error = 'unknown error';
1030 if ( exists $params->{message} ) {
1031 $error = $params->{message};
1033 # remove newline from die "error message\n" which is required to not
1034 # have the filename and line number in the error text
1037 push( @{ $c->stash->{_dbic_crud_errors} }, $error );
1040 =method_protected get_errors
1042 Returns all of the errors stored in the stash.
1047 my ( $self, $c ) = @_;
1048 die 'Catalyst app object missing'
1050 return $c->stash->{_dbic_crud_errors};
1053 =method_protected has_errors
1055 Returns true if errors are stored in the stash.
1060 my ( $self, $c ) = @_;
1061 die 'Catalyst app object missing'
1063 return exists $c->stash->{_dbic_crud_errors};
1068 Easily provide common API endpoints based on your L<DBIx::Class> schema classes.
1069 Module provides both RPC and REST interfaces to base functionality.
1070 Uses L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize> to
1071 serialize response and/or deserialise request.
1075 This document describes base functionlity such as list, create, delete, update
1076 and the setting of config attributes. L<Catalyst::Controller::DBIC::API::RPC>
1077 and L<Catalyst::Controller::DBIC::API::REST> describe details of provided
1078 endpoints to those base methods.
1080 You will need to create a controller for each schema class you require API
1081 endpoints for. For example if your schema has Artist and Track, and you want to
1082 provide a RESTful interface to these, you should create
1083 MyApp::Controller::API::REST::Artist and MyApp::Controller::API::REST::Track
1084 which both subclass L<Catalyst::Controller::DBIC::API::REST>.
1085 Similarly if you wanted to provide an RPC style interface then subclass
1086 L<Catalyst::Controller::DBIC::API::RPC>. You then configure these individually
1087 as specified in L</CONFIGURATION>.
1089 Also note that the test suite of this module has an example application used to
1090 run tests against. It maybe helpful to look at that until a better tutorial is
1093 =head2 CONFIGURATION
1095 Each of your controller classes needs to be configured to point at the relevant
1096 schema class, specify what can be updated and so on, as shown in the L</SYNOPSIS>.
1098 The class, create_requires, create_allows and update_requires parameters can
1099 also be set in the stash like so:
1101 sub setup :Chained('/api/rpc/rpc_base') :CaptureArgs(1) :PathPart('any') {
1102 my ($self, $c, $object_type) = @_;
1104 if ($object_type eq 'artist') {
1105 $c->stash->{class} = 'MyAppDB::Artist';
1106 $c->stash->{create_requires} = [qw/name/];
1107 $c->stash->{update_allows} = [qw/name/];
1109 $self->push_error($c, { message => "invalid object_type" });
1113 $self->next::method($c);
1116 Generally it's better to have one controller for each DBIC source with the
1117 config hardcoded, but in some cases this isn't possible.
1119 Note that the Chained, CaptureArgs and PathPart are just standard Catalyst
1120 configuration parameters and that then endpoint specified in Chained - in this
1121 case '/api/rpc/rpc_base' - must actually exist elsewhere in your application.
1122 See L<Catalyst::DispatchType::Chained> for more details.
1124 Below are explanations for various configuration parameters. Please see
1125 L<Catalyst::Controller::DBIC::API::StaticArguments> for more details.
1129 Whatever you would pass to $c->model to get a resultset for this class.
1130 MyAppDB::Track for example.
1132 =head3 resultset_class
1134 Desired resultset class after accessing your model. MyAppDB::ResultSet::Track
1135 for example. By default, it's DBIx::Class::ResultClass::HashRefInflator.
1136 Set to empty string to leave resultset class without change.
1140 Controls where in stash request_data should be stored, and defaults to 'response'.
1144 By default, the response data of multiple item actions is serialized into
1145 $c->stash->{$self->stash_key}->{$self->data_root} and data_root defaults to
1146 'list' to preserve backwards compatibility. This is now configuable to meet
1147 the needs of the consuming client.
1151 By default, the response data of single item actions is serialized into
1152 $c->stash->{$self->stash_key}->{$self->item_root} and item_root default to
1155 =head3 use_json_boolean
1157 By default, the response success status is set to a string value of "true" or
1158 "false". If this attribute is true, JSON's true() and false() will be used
1159 instead. Note, this does not effect other internal processing of boolean values.
1161 =head3 count_arg, page_arg, select_arg, search_arg, grouped_by_arg, ordered_by_arg, prefetch_arg, as_arg, total_entries_arg
1163 These attributes allow customization of the component to understand requests
1164 made by clients where these argument names are not flexible and cannot conform
1165 to this components defaults.
1167 =head3 create_requires
1169 Arrayref listing columns required to be passed to create in order for the
1170 request to be valid.
1172 =head3 create_allows
1174 Arrayref listing columns additional to those specified in create_requires that
1175 are not required to create but which create does allow. Columns passed to create
1176 that are not listed in create_allows or create_requires will be ignored.
1178 =head3 update_allows
1180 Arrayref listing columns that update will allow. Columns passed to update that
1181 are not listed here will be ignored.
1185 Arguments to pass to L<DBIx::Class::ResultSet/select> when performing search for
1190 Complements arguments passed to L<DBIx::Class::ResultSet/select> when performing
1191 a search. This allows you to specify column names in the result for RDBMS
1194 =head3 select_exposes
1196 Columns and related columns that are okay to return in the resultset since
1197 clients can request more or less information specified than the above select
1202 Arguments to pass to L<DBIx::Class::ResultSet/prefetch> when performing search
1205 =head3 prefetch_allows
1207 Arrayref listing relationships that are allowed to be prefetched.
1208 This is necessary to avoid denial of service attacks in form of
1209 queries which would return a large number of data
1210 and unwanted disclosure of data.
1214 Arguments to pass to L<DBIx::Class::ResultSet/group_by> when performing search
1219 Arguments to pass to L<DBIx::Class::ResultSet/order_by> when performing search
1222 =head3 search_exposes
1224 Columns and related columns that are okay to search on. For example if only the
1225 position column and all cd columns were to be allowed
1227 search_exposes => [qw/position/, { cd => ['*'] }]
1229 You can also use this to allow custom columns should you wish to allow them
1230 through in order to be caught by a custom resultset. For example:
1232 package RestTest::Controller::API::RPC::TrackExposed;
1238 search_exposes => [qw/position title custom_column/],
1241 and then in your custom resultset:
1243 package RestTest::Schema::ResultSet::Track;
1245 use base 'RestTest::Schema::ResultSet';
1249 my ($clause, $params) = @_;
1252 if (my $pretend = delete $clause->{custom_column}) {
1253 $clause->{'cd.year'} = $pretend;
1255 my $rs = $self->SUPER::search(@_);
1260 Arguments to pass to L<DBIx::Class::ResultSet/rows> when performing search for
1265 Arguments to pass to L<DBIx::Class::ResultSet/page> when performing search for
1270 By default the create, delete and update actions will not return anything apart
1271 from the success parameter set in L</end>, often this is not ideal but the
1272 required behaviour varies from application to application. So normally it's
1273 sensible to write an intermediate class which your main controller classes
1276 For example if you wanted create to return the JSON for the newly created
1277 object you might have something like:
1279 package MyApp::ControllerBase::DBIC::API::RPC;
1282 BEGIN { extends 'Catalyst::Controller::DBIC::API::RPC' };
1284 sub create :Chained('setup') :Args(0) :PathPart('create') {
1285 my ($self, $c) = @_;
1287 # $c->req->all_objects will contain all of the created
1288 $self->next::method($c);
1290 if ($c->req->has_objects) {
1291 # $c->stash->{$self->stash_key} will be serialized in the end action
1292 $c->stash->{$self->stash_key}->{$self->data_root} = [ map { { $_->get_inflated_columns } } ($c->req->all_objects) ] ;
1296 package MyApp::Controller::API::RPC::Track;
1299 BEGIN { extends 'MyApp::ControllerBase::DBIC::API::RPC' };
1302 It should be noted that the return_object attribute will produce the above
1303 result for you, free of charge.
1305 Similarly you might want create, update and delete to all forward to the list
1306 action once they are done so you can refresh your view. This should also be
1309 If more extensive customization is required, it is recommened to peer into the
1310 roles that comprise the system and make use
1314 It should be noted that version 1.004 and above makes a rapid depature from the
1315 status quo. The internals were revamped to use more modern tools such as Moose
1316 and its role system to refactor functionality out into self-contained roles.
1318 To this end, internally, this module now understands JSON boolean values (as
1319 represented by the JSON module) and will Do The Right Thing in handling those
1320 values. This means you can have ColumnInflators installed that can covert
1321 between JSON booleans and whatever your database wants for boolean values.
1323 Validation for various *_allows or *_exposes is now accomplished via
1324 Data::DPath::Validator with a lightly simplified, via a subclass of
1325 Data::DPath::Validator::Visitor.
1327 The rough jist of the process goes as follows: Arguments provided to those
1328 attributes are fed into the Validator and Data::DPaths are generated.
1329 Then incoming requests are validated against these paths generated.
1330 The validator is set in "loose" mode meaning only one path is required to match.
1331 For more information, please see L<Data::DPath::Validator> and more specifically
1332 L<Catalyst::Controller::DBIC::API::Validator>.
1335 Transactions are used. The stash is put aside in favor of roles applied to the
1336 request object with additional accessors.
1337 Error handling is now much more consistent with most errors immediately detaching.
1338 The internals are much easier to read and understand with lots more documentation.
1341 The SQL::Abstract -and, -not and -or operators are supported.