1+ use super :: { Api , Result } ;
2+ use serde_json:: { json, Value } ;
3+
4+ pub struct Client {
5+ client : reqwest:: Client ,
6+ api : Api ,
7+ }
8+
9+ impl Client {
10+ pub fn new ( client : reqwest:: Client , id : Option < String > ) -> Client {
11+ Client {
12+ client,
13+ api : if let Some ( id) = id {
14+ Api :: Production ( id)
15+ } else {
16+ Api :: Mock
17+ } ,
18+ }
19+ }
20+
21+ pub async fn search ( & self , parameters : & Value ) -> Result < Value > {
22+ self . get ( "search" , parameters) . await
23+ }
24+
25+ pub async fn typeahead ( & self , parameters : & Value ) -> Result < Value > {
26+ self . get ( "typeahead" , parameters) . await
27+ }
28+
29+ pub async fn episode_by_id ( & self , id : & str , parameters : & Value ) -> Result < Value > {
30+ self . get ( & format ! ( "episodes/{}" , id) , parameters) . await
31+ }
32+
33+ pub async fn episodes ( & self , ids : & [ & str ] , parameters : & Value ) -> Result < Value > {
34+ self . post ( "episodes" , & parameters. with ( "ids" , & ids. join ( "," ) . as_str ( ) ) )
35+ . await
36+ }
37+
38+ pub async fn genres ( & self , parameters : & Value ) -> Result < Value > {
39+ self . get ( "genres" , parameters) . await
40+ }
41+
42+ async fn get ( & self , endpoint : & str , parameters : & Value ) -> Result < Value > {
43+ Ok ( self
44+ . client
45+ . get ( format ! ( "{}/{}" , self . api. url( ) , endpoint) )
46+ . query ( parameters)
47+ . send ( )
48+ . await ?
49+ . json ( )
50+ . await ?)
51+ }
52+
53+ async fn post ( & self , endpoint : & str , parameters : & Value ) -> Result < Value > {
54+ Ok ( self
55+ . client
56+ . post ( format ! ( "{}/{}" , self . api. url( ) , endpoint) )
57+ . header ( "Content-Type" , "application/x-www-form-urlencoded" )
58+ . body ( serde_json:: to_string ( & parameters) ?) // TODO: switch to URL encoding
59+ . send ( )
60+ . await ?
61+ . json ( )
62+ . await ?)
63+ }
64+ }
65+
66+ trait AddField {
67+ fn with ( & self , key : & str , value : & str ) -> Self ;
68+ }
69+
70+ impl AddField for Value {
71+ fn with ( & self , key : & str , value : & str ) -> Self {
72+ let mut p = self . clone ( ) ;
73+ p[ key] = json ! ( value) ;
74+ p
75+ }
76+ }
0 commit comments