diff options
| author | Joelle Maslak <jmaslak@antelope.net> | 2019-07-21 12:50:01 -0600 |
|---|---|---|
| committer | Joelle Maslak <jmaslak@antelope.net> | 2019-07-21 12:50:01 -0600 |
| commit | 20f4ff941f61c2e6a7e9f560dd213ffb31899538 (patch) | |
| tree | 89cec2c36cc32fbc04ebc944282760f38832c23c | |
| parent | 2a0b12495163fcd0f3f0d0e1bb0a7d0af82bcdd0 (diff) | |
| download | perlweeklychallenge-club-20f4ff941f61c2e6a7e9f560dd213ffb31899538.tar.gz perlweeklychallenge-club-20f4ff941f61c2e6a7e9f560dd213ffb31899538.tar.bz2 perlweeklychallenge-club-20f4ff941f61c2e6a7e9f560dd213ffb31899538.zip | |
Add 17.3 solution
| -rwxr-xr-x | challenge-017/joelle-maslak/perl6/ch-3.p6 | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/challenge-017/joelle-maslak/perl6/ch-3.p6 b/challenge-017/joelle-maslak/perl6/ch-3.p6 new file mode 100755 index 0000000000..99febae04e --- /dev/null +++ b/challenge-017/joelle-maslak/perl6/ch-3.p6 @@ -0,0 +1,73 @@ +#!/usr/bin/env perl6 +use v6; + +use Cro::HTTP::Client; + +sub MAIN( + UInt:D $chapter, + UInt:D $verse, + Str:D :$config-file? = $*HOME.add(".bhagavad-gita").Str, + Str:D :$base-url = 'https://bhagavadgita.io/', +) { + say get-verse(:$config-file, :$base-url, :$chapter, :$verse); +} + +sub get-client-id(Str:D $config-file -->Str:D) { + my @lines = $config-file.IO.lines().grep( *.chars > 0 ); + die "Config-file ($config-file) must consist of two lines" if @lines.elems ≠ 2; + + return @lines.first; +} + +sub get-client-secret(Str:D $config-file -->Str:D) { + my @lines = $config-file.IO.lines().grep( *.chars > 0 ); + die "Config-file ($config-file) must consist of two lines" if @lines.elems ≠ 2; + + return @lines[1]; +} + + +sub get-verse ( + UInt:D :$chapter, + UInt:D :$verse, + Str:D :$base-url, + Str:D :$config-file, +) { + my $id = get-client-id($config-file); + my $secret = get-client-secret($config-file); + + my $token-client = Cro::HTTP::Client.new( + base-uri => $base-url, + content-type => 'application/x-www-form-urlencoded', + ); + + my $resp = await $token-client.post( + 'auth/oauth/token', + body => %( + client_id => $id, + client_secret => $secret, + grant_type => "client_credentials", + scope => "verse chapter" + ) + ); + my $response = await $resp.body; + + my $client = Cro::HTTP::Client.new( + http => 1.1, + base-uri => $base-url, + headers => [ Authorization => "Bearer $response<access_token>" ], + content-type => 'application/json', + ); + $resp = await $client.get("api/v1/chapters/$chapter/verses/$verse"); + my $json = await $resp.body; + + return $json<text>; + + CATCH { + when X::Cro::HTTP::Error { + my $body = await .response.body; + die "Error from API endpoint: $body<message>"; + } + } +} + |
