Acme-CPANModulesBundle-Import-PerlDancerAdvent-2018

 view release on metacpan or  search on metacpan

devdata/http_advent.perldancer.org_2018_22  view on Meta::CPAN



<!-- Grab Google CDN's jQuery. fall back to local if necessary -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">/* <![CDATA[ */
    !window.jQuery && document.write('<script src="/javascripts/jquery.js"><\/script>')
/* ]]> */</script>

<!-- Prettyfy -->
<link href="/css/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="/javascripts/prettify.js"></script>

</head>
<body onload="prettyPrint()">
<div id="page">

<div id="sidebar">
<a href="/" class="homelink">Dancer Advent Calendar</a><br />

<p>
The PerlDancer Advent Calendar is a community-driven project that aims 
to showcase the Dancer Perl web framework.
</p>

<p>
Each day of December until Christmas, one article about Dancer. Stay tuned for new moves!
</p>

<ul id="sidebar-items">
<li>
    <h3>About Dancer</h3>
    <ul class="links">
        <li><a href="http://www.perldancer.org/">Dancer homepage</a></li>
        <li><a href="http://twitter.com/PerlDancer">Official Twitter</a></li>
        <li><a href="http://github.com/PerlDancer/Dancer">Dancer on GitHub</a></li>
        <li><a href="http://github.com/PerlDancer/Dancer2">Dancer 2 on GitHub</a></li>
        <li><a class="feed" href="/feed/2018">RSS</a></li>
    </ul>
</li>
</ul>
</div>


<div id="content">
<div class="pod-document"><h1><a name="parameter_testing_with_dancer2__plugin__paramtypes"></a>Parameter testing with Dancer2::Plugin::ParamTypes</h1>

<p>The most common web code you will ever write is testing your parameters.
You might as well have a good way to do this.</p>
<h2><a name="in_the_old_ages"></a>In the old ages</h2>

<p>Way back then, we used to write code to check all of our arguments.</p>
<p>If we had a route that includes some ID, we would check that we
received it and that it matches the type we want. We would then decide
what to do if it doesn't match. Over time, we would clean up and
refactor, and try to reuse the checking code.</p>
<p>For example:</p>
<pre class="prettyprint">use Dancer2;
get '/:id' =&gt; sub {
    my $id = route_parameters-&gt;{'id'};
    if ( $id !~ /^[0-9]+$/ ) {
        send_error 'Bad ID' =&gt; 400;
    }

    # optional
    my $action = query_parameters-&gt;{'action'};
    unless ( defined $action &amp;&amp; length $action ) {
        send_error 'Bad Action' =&gt; 400;
    }

    # use $id and maybe $action
};</pre>

<p>The more parameters we have, the more annoying it is to write these
tests.</p>
<p>But what's more revealing here is that this validation code is not
actually part of our web code. It's input validation <i>for</i> our web
code.</p>
<h2><a name="a_different_perspective"></a>A different perspective</h2>

<p>What if - instead of having to write all of this code - we maintained
the Dancer2 spirit and allowed you to <b>declare</b> what your validation
rules are, and have Dancer2 do the work for you?</p>
<p>Lucky you! We have done just that with <a href="https://metacpan.org/module/Dancer2::Plugin::ParamTypes">Dancer2::Plugin::ParamTypes</a>!</p>
<h3><a name="register_your_own_types"></a>Register your own types</h3>

<p>There are normally two options that type check syntax give you:</p>
<blockquote>
<p>We didn't want to create our own type system or type validations. There
are already plenty of good ones.</p>
<blockquote>
<p>And we didn't want to tie the plugin with a specific type system
because it might not suit you.</p>
</blockquote>
<p>Instead, we picked a third option: Allowing you to connect it with
whatever you want.</p>
<pre class="prettyprint">use Dancer2;
use Dancer2::Plugin::ParamTypes;

# register an 'Int'
register_type_check 'Int' =&gt; sub { $_[0] =~ /^[0-9]+$/ };</pre>

<p>You could also register existing type systems:</p>
<pre class="prettyprint">use MooX::Types::MooseLike::Base qw&lt; Int &gt;;
reigster_type_checks(
    'Int' =&gt; sub { Int()-&gt;( $_[0] ) },
);</pre>

</blockquote>
<h3><a name="using_your_now_available_types"></a>Using your now-available types</h3>

<p>Once you register all the types you want, you could use them in your
code with a simple stanza.</p>
<pre class="prettyprint">use Dancer2::Plugin::ParamTypes;
register_type_check(...);

# Indented to make it more readable
get '/:id' =&gt; with_types [
                 [ 'route', 'id', 'Int' ],
    'optional =&gt; [ 'query', 'action', 'Str' ],
] =&gt; sub {
    my $id = route_parameters-&gt;{'id'};

    # do something with $id because we know it exists and validated

    if ( my $action = query_parameters-&gt;{'action'} ) {
        # if it exists, we know it's validated
    }

devdata/http_advent.perldancer.org_2018_22  view on Meta::CPAN

# Register all of our own type checks at build time
sub BUILD {
    my $self = shift;

    $self-&gt;register_type_check 'Str'         =&gt; sub {...};
    $self-&gt;register_type_check 'ShortStr'    =&gt; sub {...};
    $self-&gt;register_type_check 'PositiveInt' =&gt; sub {...};
    $self-&gt;register_type_check 'SHA1'        =&gt; sub {...};

    # Maybe more?
    ...
}</pre>

<p>Now we have our own plugin that also provides <code>with_types</code> which uses
the original plugin with a set of registered type checks.</p>
<pre class="prettyprint">package MyApp;
use Dancer2;
use Dancer2::Plugin::MyCommonTypes;

post '/:entity/update/:id' =&gt; with_types [
    [ 'route', 'entity',  'Str'         ],
    [ 'route', 'id',      'PositiveInt' ],
    [ 'body',  'message', 'Str'         ],

    'optional' =&gt; [ 'body', 'sid', 'SHA1' ],
] =&gt; sub {
    my ( $entity, $id ) = @{ route_parameters() }{qw&lt; id entity &gt;};
    my $message = body_parameters-&gt;{'message'};
    my $sid     = body_parameters-&gt;{'sid'} || '';

    # everything is validated and required parameters are checked
    ...
};</pre>

<h2><a name="could_i_do_more_with_it"></a>Could I do more with it?</h2>

<p>Absolutely!</p>
<h3><a name="handle_multiple_sources"></a>Handle multiple sources</h3>

<p>Normally, you would dictate to a user how they should send their
paramters (in the query, in the body, or as part of the path - in the
route), but sometimes you cannot control this. Maybe you're maintaining
an old interface or supporting outdated APIs.</p>
<p><a href="https://metacpan.org/module/Dancer2::Plugin::ParamTypes">Dancer2::Plugin::ParamTypes</a> is flexible enough to support multiple
sources for an argument:</p>
<pre class="prettyprint">any [ 'get', 'post' ] =&gt; '/:entity/:id' =&gt; with_types [
    [ 'route',             'entity', 'Str' ],
    [ 'route',             'id',     'PositiveInt' ],
    [ [ 'query', 'body' ], 'format', 'Str' ],

    'optional' =&gt; [ 'body', 'sid', 'SHA1' ],
] =&gt; sub {...};</pre>

<p>In this form, the parameter <code>format</code> can be provided either in the
query string or in the body, because your route might be either a
<b>GET</b> or a <b>POST</b>.</p>
<h3><a name="register_type_actions"></a>Register type actions</h3>

<p>Type checking itself is the main role of this plugin, but you can also
control how it behaves.</p>
<p>The default action to perform when a type check fails is to error out,
but you can decide to act differently by registering a different
action.</p>
<pre class="prettyprint">register_type_action 'SoftError' =&gt; sub {
    my ( $self, $details ) = @_;

    warning "Parameter $details-&gt;{'name'} from $details-&gt;{'source'} "
          . "failed checking for type $details-&gt;{'type'}, called "
          . "action $details-&gt;{'action'}";

    return;
};

get '/:id' =&gt; with_types [
    [ 'query', 'age', 'Int', 'SoftError',
] =&gt; sub {...};</pre>

<p>On a bad <code>age</code> parameter, it will print out the following warning:</p>
<pre class="prettyprint">Parameter age from query failed checking for type Int, called action SoftError</pre>

<p>This means you can also register a set of actions that you want to call
in different cases.</p>
<h2><a name="conclusion"></a>Conclusion</h2>

<p><a href="https://metacpan.org/module/Dancer2::Plugin::ParamTypes">Dancer2::Plugin::ParamTypes</a> allows you to define your own types and
your own actions, to create your own plugin that helps you maintain
reusability and consistency across your application with fewer code
duplication and less effort.</p>
<h2><a name="author"></a>Author</h2>

<p>This article has been written by Sawyer X for the Perl
Dancer Advent Calendar 2018.</p>
<h2><a name="copyright"></a>Copyright</h2>

<p>No copyright retained. Enjoy.</p>
<p>2018 // Sawyer X <code>&lt;xsawyerx@cpan.org&gt;</code></p>
</div>

 <div id="disqus_thread"></div>
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
        var disqus_shortname = 'danceradvent'; // required: replace example with your forum shortname

        /* * * DON'T EDIT BELOW THIS LINE * * */
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>




</div>



<div id="footer">
Powered by the  



( run in 0.722 second using v1.01-cache-2.11-cpan-39bf76dae61 )