NAME
CatalystX::QueryModel - Inflate Models from a Request Content Body or from URL Query Parameters
SYNOPSIS
An example Catalyst Request Model:
package Example::Model::PagingQuery;
use Moose;
use CatalystX::QueryModel;
extends 'Catalyst::Model';
namespace 'user';
has status => (is=>'ro', property=>1);
has page => (is=>'ro', property=>1);
__PACKAGE__->meta->make_immutable();
Using it in a controller:
package Example::Controller::User;
use Moose;
use MooseX::MethodAttributes;
extends 'Catalyst::Controller';
sub root :Chained(/root) PathPart('user') CaptureArgs(0) { }
sub list :GET Chained('root') PathPart('') Args(0) Does(QueryModel) QueryModel(PagingQuery) {
my ($self, $c, $query_model) = @_;
}
__PACKAGE__->meta->make_immutable;
Now if the incoming GET looks like this:
[debug] Query Parameters are:
.-------------------------------------+--------------------------------------.
| Parameter | Value |
+-------------------------------------+--------------------------------------+
| user.page | 2 |
| user.status | active |
'-------------------------------------+--------------------------------------'
The object instance $query_model
would look like:
say $query_model->page; # 2
say $query_model->status; # 'active'
And $query_model
has additional helper public methods to query attributes marked as request fields (via the property
attribute field) which you can read about below.
DESCRIPTION
This is very similiar to <CatalystX::RequestModel> but for query parameters that are part of the request URL. Basically we are mapping the query params hash to a object which makes it more robust to access and gives you a place to do any sort of query parameter logic. Can neaten up your controllers and give you more reusable code.
Query options
When you include "use CatalystX::QueryModel" we apply the role CatalystX::QueryModel::DoesQueryModel to you model, which gives you some useful methods as well as the ability to store the meta data needed to properly mapped parsed query parameters to your model. You also get some imported subroutines and a new field on your attribute declarations:
namespace
: This is an optional imported subroutine which allows you to declare the namespace under which we expect to find the attribute mappings. This can be useful if your fields are not top level in your request content body (as in the example given above). This is optional and if you leave it off we just assume all fields are in the top level of the parsed data hash that you content parser builds based on whatever is in the content body.
If you declare a namespace in a query model by default we don't throw an error if the namespace is missing (unlike in request models) because I think for query parameters this is the common case where the query is not required (for example in a paged list screen when you default to page 1 when a page is not given). If you want the namespace required you can declare it so like this
namespace paging => (required=>1);
content_type
: This is the request content type which this model is designed to handle. For now you can only declare one content type per model (if your endpoint can handle more than one content type you'll need for now to define a request model for each one; I'm open to changing this to allow one than one content type per request model, but I need to see your use cases for this before I paint myself into a corner codewise).
This is also an optional check for query parameters.
property
: This is a new field allowed on your attribute declarations. Setting its value to 1
(as in the example above) just means to use all the default settings for the declared content_type but you can declare this as a hashref instead if you have special handling needs. For example:
has notes => (is=>'ro', property=>+{ expand=>'JSON' });
Here's the current list of property settings and what they do. You can also request the test cases for more examples:
- name
-
The name of the field in the request body we are mapping to the request model. The default is to just use the name of the attribute.
- omit_empty
-
Defaults to true. If there's no matching field in the request body we leave the request model attribute empty (we don't stick an undef in there). If for some reason you don't want that, setting this to false will put an undef into a scalar fields, and an empty array into an indexed one. If has no effect on attributes that map to a submodel since I have no idea what that should be (your use cases welcomed).
- flatten
-
If the value associated with a field is an array, flatten it to a single value. The default is based on the body content parser. Its really a hack to deal with HTML form POST and Query parameters since the way those formats work you can't be sure if a value is flat or an array. This isn't a problem with JSON encoded request bodies. You'll need to check the docs for the Content Body Parser you are using to see what this does.
- always_array
-
Similar to
flatten
but opposite, it forces a value into an array even if there's just one value. Again mostly useful to deal with ideosyncracies of HTML form post.NOTE: The attribute property settings
flatten
andalways_array
are currently exclusive (only one of the two will apply if you supply both. Thealways_array
property always takes precedence. At some point in the future supplying both might generate an exception so its best not to do that. I'm only leaving it allowed for now since I'm not sure there's a use case for both. - boolean
-
Defaults to false. If true will convert value to the common Perl convention 0 is false, 1 is true. The way this is converted is partly dependent on your content body parser.
- expand
-
Example the value into a data structure by parsing it. Right now there's only one value this will take, which is
JSON
and will then parse the value into a structure using a JSON parser. Again this is mostly useful for HTML form posting and coping with some limitations you have in classic HTML form input types.
Setting a required attribute
Generally it's best to not mark attributes which map to request properties as required and to handled anything like thia via your validation layer so that you can provide more useful feedback to your application users. If you do need to mark something required in order for your request model to be valid, please note that we capture the exception created by Moo/se and throw CatalystX::RequestModel::Utils::BadRequest. If you are using CatalystX::Errors this will get rendered as a HTTP 400 Bad Request; otherwise you just get the generic Catalyst HTTP 500 Server Error or as you might have written in your custom error handling code.
Nested and Indexed attributes
These work the same as in CatalystX::RequestModel
METHODS
Please see CatalystX::QueryModel::DoesQueryModel for the public API details.
EXCEPTIONS
This class can throw the following exceptions. Please note all exceptions are compatible with CatalystX::Errors to make it easy and consistent to convert errors to actual error responses.
Bad Request
If your request generates an exception when trying to instantiate your model (basically when calling ->new on it) we capture that error, log the error and throw a CatalystX::RequestModel::Utils::BadRequest
Invalid Request Content Type
If the incoming content body doesn't have a content type header that matches one of the available content body parsers then we throw an CatalystX::RequestModel::Utils::InvalidContentType. This will get interpretated as an HTTP 415 status client error if you are using CatalystX::Errors.
AUTHOR
John Napiorkowski <jjnapiork@cpan.org>
COPYRIGHT
2022
LICENSE
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.