summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/WebService/ForecastIo.pm85
1 files changed, 85 insertions, 0 deletions
diff --git a/lib/WebService/ForecastIo.pm b/lib/WebService/ForecastIo.pm
new file mode 100644
index 0000000..fd6bcb8
--- /dev/null
+++ b/lib/WebService/ForecastIo.pm
@@ -0,0 +1,85 @@
+package WebService::ForecastIo;
+use Moose;
+use MooseX::Types::URI 'Uri';
+use MooseX::Params::Validate;
+use Moose::Util::TypeConstraints;
+
+has base_uri => (
+ is => 'ro',
+ isa => Uri,
+ coerce => 1,
+ default => 'https://api.forecast.io/forecast',
+);
+
+has api_key => (
+ is => 'ro',
+ isa => 'Str',
+ required => 1,
+);
+
+has user_agent => (
+ is => 'ro',
+ isa => duck_type(['get']),
+ lazy_build => 1,
+);
+sub _build_user_agent {
+ require LWP::UserAgent;
+ my $agent = LWP::UserAgent->new(
+ agent => __PACKAGE__ . ' version ' . ($WebService::ForecastIo::VERSION // 'devel' ),
+ env_proxy => 1,
+ keep_alive => 1,
+ );
+ $agent->default_header( 'Accept-Encoding' => 'gzip' );
+ return $agent;
+}
+
+sub _make_request_uri {
+ my ($self,%opts) = @_;
+
+ my ($lat,$lon,$time) = delete @opts{qw(latitude longitude time)};
+
+ my $req_uri = $self->base_uri->clone;
+ $req_uri->path_segments(
+ grep { length($_)>0 }
+ $req_uri->path_segments,
+ $self->api_key,
+ "$lat,$lon",
+ ( defined $time ? $time : () ),
+ );
+
+ if ($opts{exclude}) {
+ $opts{exclude} = join ',',@{$opts{exclude}};
+ }
+
+ $req_uri->query_form(\%opts);
+
+ return $req_uri;
+}
+
+enum my $units_type=__PACKAGE__.'::units',
+ [qw(us si ca uk auto)];
+enum my $block_type=__PACKAGE__.'::block',
+ [qw(currently minutely hourly daily alerts flags)];
+
+sub request {
+ my ($self,%opts) = validated_hash(
+ \@_,
+ latitude => { isa => 'Num' },
+ longitude => { isa => 'Num' },
+ time => { isa => 'Num|Str', optional => 1 },
+ units => { isa => $units_type, default => 'si' },
+ exclude => { isa => "ArrayRef[$block_type]", default => sub { [] } },
+ );
+
+ my $uri = $self->_make_request_uri(%opts);
+
+ my $response = $self->user_agent->get($uri);
+ if ($response->is_success) {
+ return $response->decoded_content;
+ }
+ else {
+ die $response->status_line
+ }
+}
+
+1;