summary refs log tree commit diff
path: root/lib/Net/HTTP/API/Spec.pm
blob: 6ee175b69c6103f08bd3e798e504cc028cd6ec1a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package Net::HTTP::API::Spec;

use Moose;

use IO::All;
use JSON;
use Carp;
use Try::Tiny;

use Net::HTTP::API::Core;

sub new_from_spec {
    my ($class, $spec_file) = @_;

    # TODO:
    # - load from an url
    if (! -f $spec_file) {
        Carp::confess ("$spec_file does not exists");
    }

    my ($content, $spec);

    $content < io($spec_file);

    try {
        $spec = JSON::decode_json($content);
    }
    catch {
        Carp::Confess( "unable to parse JSON spec: " . $_ );
    };

    my $net_api_class =
      Class::MOP::Class->create_anon_class(
          superclasses => ['Net::HTTP::API::Core']);

    my $net_api_object;
    try {
        $net_api_object = $net_api_class->new_object;

        $net_api_object = _declare_api($net_api_object, $spec->{declare});
        $net_api_object = _add_methods($net_api_object, $spec->{methods});

    }catch{
        Carp::Confess("unable to create new Net::HTTP::API object: ".$_);
    };

    return $net_api_object;
}

sub _declare_api {
    my ($api, $declaration_spec) = @_;

    foreach my $k (keys %$declaration_spec) {
        $api->meta->set_api_option($k => $declaration_spec->{$k});
    }
    $api;
}

sub _add_methods {
    my ($class, $methods_spec) = @_;

    foreach my $method_name (keys %$methods_spec) {
        $class->meta->add_net_api_method($method_name,
            %{$methods_spec->{$method_name}});
    }
    $class;
}

1;