App-SahUtils

 view release on metacpan or  search on metacpan

script/validate-with-sah  view on Meta::CPAN

        no_modules => {
            summary => 'Generate Perl validator that does not use modules',
            schema => ['bool', is=>1],
            tags => ['category:validator-specification'],
            # XXX only relevant when compiler=perl
        },
        compiler => {
            summary => "Select compiler",
            schema=>['str*', in=>[qw/perl js/]],
            default => 'perl',
            cmdline_aliases => {C=>{}},
            tags => ['category:validator-specification'],
        },
        coerce => {
            summary => 'Whether to generate coercion code',
            'summary.alt.bool.not' => 'Generate validator that does not do coercions',
            schema => 'bool',
            default => 1,
            tags => ['category:validator-specification'],
        },

        linenum => {
            summary => 'When showing source code, add line numbers',
            schema=>['bool', is=>1],
            cmdline_aliases => {l=>{}},
            tags => ['category:output'],
        },
    },
    examples => [
        {
            src => q([[prog]] '"int*"' 42),
            src_plang => 'bash',
            summary => 'Should succeed and return empty string',
        },
        {
            src => q([[prog]] '"int*"' '"x"'),
            src_plang => 'bash',
            summary => 'Should show an error message because "x" is not int',
        },
        {
            src => q([[prog]] '["int","min",1,"max",10]' --multiple-data-json '[-4,7,15]' --return-type bool),
            src_plang => 'bash',
            summary => 'Validate multiple data, should return "", 1, ""',
        },
        {
            src => q([[prog]] '["int","min",1,"max",10]' --multiple-data-json '[-4,7,15]' -d),
            src_plang => 'bash',
            summary => 'Show data alongside with result',
        },
        {
            src => q([[prog]] '["int","min",1,"max",10]' -c -l),
            src_plang => 'bash',
            summary => 'Show validator Perl source code only, with line number',
        },
        {
            src => q([[prog]] '["date"]' -c --no-coerce),
            src_plang => 'bash',
            summary => 'Show validator Perl source code, with no coercion code (the validator will only accept epochs)',
        },
        {
            src => q([[prog]] '["date",{"x.perl.coerce_to":"DateTime"}]' -c --no-coerce),
            src_plang => 'bash',
            summary => 'Show validator Perl source code, with no coercion code (the validator will only accept DateTime objects)',
        },
        {
            src => q([[prog]] '["int","min",1,"max",10]' -c -C js),
            src_plang => 'bash',
            summary => 'Show validator JavaScript code',
        },
        {
            src => q([[prog]] '["int","min",1,"max",10]' -C js -c -l),
            src_plang => 'bash',
            summary => 'Show validator JS source code only, with line number',
        },
        {
            src => q{[[prog]] -f schema1.json '["data"]'},
            src_plang => 'bash',
            summary => 'Load schema from file',
            test => 0,
            'x.doc.show_result' => 0,
        },
        {
            src => q{[[prog]] -f schema1.json --multiple-data-file datafile --data-file-type json},
            src_plang => 'bash',
            summary => 'Load schema and data from file',
            test => 0,
            'x.doc.show_result' => 0,
        },
    ],
};
sub validate_with_sah {
    my %args = @_;

    my $res;
  GET_RESULT:
    {
        my $schema;
        if (defined $args{schema}) {
            if (defined $args{schema_file}) {
                $res = [400, "Please specify either 'schema' or 'schema_file', not both"];
                last GET_RESULT;
            }
            $schema = $args{schema};
        } elsif (defined $args{schema_file}) {
            my $path = $args{schema_file};
            my $type = $args{schema_file_type};
            if (!$type) {
                if ($path =~ /\b(json)$/i) { $type = 'json' }
                elsif ($path =~ /\b(yaml|yml)$/i) { $type = 'yaml' }
                elsif ($path =~ /\b(perl|pl)$/i) { $type = 'perl' }
                else { $type = 'json' }
            }
            if ($type eq 'json') {
                require File::Slurper;
                require JSON::MaybeXS;
                my $ct = File::Slurper::read_text($path);
                $schema = JSON::MaybeXS->new->allow_nonref->decode($ct);
            } elsif ($type eq 'yaml') {
                require YAML::XS;
                $schema = YAML::XS::LoadFile($path);
            } elsif ($type eq 'perl') {
                require File::Slurper;
                my $ct = File::Slurper::read_text($path);

script/validate-with-sah  view on Meta::CPAN

 % validate-with-sah '["int","min",1,"max",10]' --multiple-data-json '[-4,7,15]' -d
 [
   { data => -4, result => "Must be at least 1" },
   { data => 7, result => "" },
   { data => 15, result => "Must be at most 10" },
 ]

=head2 Show validator Perl source code only, with line number

 % validate-with-sah '["int","min",1,"max",10]' -c -l
    1|do {
    2|    no warnings ('void');
    3|    require Scalar::Util::Numeric;
    4|    sub {
    5|        my ($data) = @_;
    6|        my $err_data;
    7|        my $_sahv_res = 
     |        
    9|            # skip if undef
   10|            (!defined($data) ? 1 : 
     |            
   12|            (# check type 'int'
   13|            ((Scalar::Util::Numeric::isint($data)) ? 1 : (($err_data //= "Not of type integer"),0))
     |            
   15|            &&
     |            
   17|            (# clause: min
   18|            (($data >= 1) ? 1 : (($err_data //= "Must be at least 1"),0)))
     |            
   20|            &&
     |            
   22|            (# clause: max
   23|            (($data <= 10) ? 1 : (($err_data //= "Must be at most 10"),0)))));
     |        
   25|        ($err_data //= "");
     |        
   27|        return($err_data);
   28|    }}

=head2 Show validator Perl source code, with no coercion code (the validator will only accept epochs)

 % validate-with-sah '["date"]' -c --no-coerce
 do {
     no warnings ('void');
     sub {
         my ($data) = @_;
         my $err_data;
         my $_sahv_res = 
         
             # skip if undef
             (!defined($data) ? 1 : 
             
             (# check type 'date'
             ((!ref($data) && $data =~ /\A[0-9]+\z/) ? 1 : (($err_data //= "Not of type date"),0))));
         
         ($err_data //= "");
         
         return($err_data);
     }}

=head2 Show validator Perl source code, with no coercion code (the validator will only accept DateTime objects)

 % validate-with-sah '["date",{"x.perl.coerce_to":"DateTime"}]' -c --no-coerce
 do {
     no warnings ('void');
     require Scalar::Util;
     sub {
         my ($data) = @_;
         my $err_data;
         my $_sahv_res = 
         
             # skip if undef
             (!defined($data) ? 1 : 
             
             (# check type 'date'
             ((Scalar::Util::blessed($data) && $data->isa('DateTime')) ? 1 : (($err_data //= "Not of type date"),0))));
         
         ($err_data //= "");
         
         return($err_data);
     }}

=head2 Show validator JavaScript code

 % validate-with-sah '["int","min",1,"max",10]' -c -C js
 function(data) {
     var err_data = null;
     var tmp_data = [];
     var _sahv_res = 
     
         // skip if undef
         (!!(data === undefined || data === null) ? true : 
         
         (// check type 'int'
         ((typeof(data)=='number' && Math.round(data)==data || parseInt(data)==data) ? true : (err_data = !(err_data === undefined || err_data === null) ? err_data : "Not of type integer",0))
         
         &&
         
         // set temporary data term
         ((tmp_data[0] = typeof(data)=='number' ? data : parseFloat(data)), true)
         
         &&
         
         (// clause: min
         ((tmp_data[0] >= 1) ? true : (err_data = !(err_data === undefined || err_data === null) ? err_data : "Must be at least 1",0)))
         
         &&
         
         (// clause: max
         ((tmp_data[0] <= 10) ? true : (err_data = !(err_data === undefined || err_data === null) ? err_data : "Must be at most 10",0)))
         
         &&
         
         // restore original data term
         ((tmp_data).pop(), true)));
     
     err_data = !(err_data === undefined || err_data === null) ? err_data : "";
     
     return(err_data);
 }

=head2 Show validator JS source code only, with line number

 % validate-with-sah '["int","min",1,"max",10]' -C js -c -l
    1|function(data) {
    2|    var err_data = null;
    3|    var tmp_data = [];
    4|    var _sahv_res = 
     |    
    6|        // skip if undef
    7|        (!!(data === undefined || data === null) ? true : 
     |        
    9|        (// check type 'int'
   10|        ((typeof(data)=='number' && Math.round(data)==data || parseInt(data)==data) ? true : (err_data = !(err_data === undefined || err_data === null) ? err_data : "Not of type integer",0))
     |        
   12|        &&



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