summary refs log tree commit diff
path: root/lib/Net/HTTP/Spore.pm
blob: 88ce4186640648cb6df2153a7b36dacf62b8ebc9 (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
package Net::HTTP::Spore;

use Moose;

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

use Net::HTTP::Spore::Core;

our $VERSION = 0.01;

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

    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 $spore_class =
      Class::MOP::Class->create_anon_class(
          superclasses => ['Net::HTTP::Spore::Core']);

    my $spore_object;
    try {

        my $api_base_url;
        if ( $spec->{api_base_url} && !$args{api_base_url} ) {
            $args{api_base_url} = $spec->{api_base_url};
        }
        elsif ( !$args{api_base_url} ) {
            die "api_base_url is missing!";
        }

        $spore_object = $spore_class->new_object(%args);
        $spore_object = _add_methods($spore_object, $spec->{methods});

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

    return $spore_object;
}

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

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


1;