| 1 | package Dancer::Plugin::JSON::Schema; | ||
| 2 | |||
| 3 | our $VERSION = '0.001'; # VERSION | ||
| 4 | |||
| 5 | 4 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 4 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | 4 | ▶ | use utf8; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | 4 | ▶ | use Dancer::Plugin; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | 4 | ▶ | use JSON (); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 10 | 0 | ▶ | use JSON::Schema; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 11 | use JSON::Hyper; | ||
| 12 | use Dancer qw(:syntax); | ||
| 13 | |||
| 14 | my $schemas = {}; | ||
| 15 | |||
| 16 | sub json_schema { | ||
| 17 | my ($self, $name) = plugin_args(@_); | ||
| 18 | my $cfg = plugin_setting; | ||
| 19 | |||
| 20 | if (not defined $name) { | ||
| 21 | if (keys %$cfg == 1) { | ||
| 22 | ($name) = keys %$cfg; | ||
| 23 | } elsif (keys %$cfg) { | ||
| 24 | $name = "default"; | ||
| 25 | } else { | ||
| 26 | die "No JSON Schemas are configured"; | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | return $schemas->{$name} if $schemas->{$name}; | ||
| 31 | |||
| 32 | my $options = $cfg->{$name} or die "The schema $name is not configured"; | ||
| 33 | |||
| 34 | if ( my $alias = $options->{alias} ) { | ||
| 35 | $options = $cfg->{$alias} | ||
| 36 | or die "The schema alias $alias does not exist in the config"; | ||
| 37 | return $schemas->{$alias} if $schemas->{$alias}; | ||
| 38 | } | ||
| 39 | |||
| 40 | my $schema_info = | ||
| 41 | $options->{schema_info} | ||
| 42 | // | ||
| 43 | { | ||
| 44 | map { $_, $options->{$_} } qw( | ||
| 45 | options | ||
| 46 | schema | ||
| 47 | ) | ||
| 48 | } | ||
| 49 | ; | ||
| 50 | |||
| 51 | unless ( ref $schema_info->{schema} ) { | ||
| 52 | # get the file | ||
| 53 | my $appdir = config->{appdir} // __FILE__ =~ s~(?:/blib)?/lib/Dancer/Plugin/JSON/Schema\.pm~~r; | ||
| 54 | my $fn = $appdir . '/' . $schema_info->{schema}; | ||
| 55 | open ( my $fh, '<', $fn ) or die ("Could not open schema file $fn for read"); | ||
| 56 | my $raw_json = ''; | ||
| 57 | $raw_json .= $_ while (<$fh>); | ||
| 58 | my $parsed_json = JSON::from_json($raw_json); | ||
| 59 | JSON::Hyper->new->process_includes($parsed_json, '/', undef); | ||
| 60 | $schema_info->{schema} = $parsed_json; | ||
| 61 | } | ||
| 62 | |||
| 63 | my $schema; | ||
| 64 | |||
| 65 | $schema = JSON::Schema->new( $schema_info->{schema}, $schema_info->{options} // {} ); | ||
| 66 | |||
| 67 | return $schemas->{$name} = $schema; | ||
| 68 | }; | ||
| 69 | |||
| 70 | register json_schema => \&json_schema; | ||
| 71 | |||
| 72 | register_plugin for_versions => [ 1, 2 ]; | ||
| 73 | |||
| 74 | # ABSTRACT: JSON::Schema interface for Dancer applications | ||
| 75 | |||
| 76 | |||
| 77 | 1; | ||
| 78 | |||
| 79 | __END__ | ||