1 module drocks.response;
2 
3 import std.conv           : to;
4 import std.algorithm      : map;
5 import drocks.sockhandler : SockHandler;
6 import drocks.exception   : ClientException;
7 import drocks.pair        : Pair;
8 import drocks.multivalue;
9 
10 struct Response
11 {
12 private:
13     SockHandler _sock;
14 
15 public:
16     this(SockHandler sockHandler)
17     {
18         _sock = sockHandler;
19     }
20     @disable this ();
21 
22     //void close() { _sock.close(); }
23     
24     // Raw data of response
25     string raw()
26     {
27         return _sock.readAll();
28     }
29     
30     // Cast response to bool (is response "OK")
31     bool isOk()
32     {
33         if(_sock.isValid) {
34             auto resp = _sock.readLine();
35             return (resp.length > 1) && (resp[0..2] == "OK");
36         }
37         return false;
38     }
39 
40     // Check if socket is valid
41     bool isValid() const
42     {
43         return _sock.isValid;
44     }
45     
46     // Get single value of response
47     string getValue()
48     {
49         if(!_sock.isValid) {
50             return null;
51         }
52 
53         auto val_len_str = _sock.readLine();
54         if(!val_len_str.length) {
55             return null;
56         }
57 
58         auto val_len = val_len_str.to!int;
59         if(val_len < 0 || !_sock.isValid) {
60             return null;
61         }
62 
63         auto rez = val_len ? _sock.read(val_len).idup : "";
64         if(!val_len) {
65             _sock.getChar(); // retrieve char '\n'
66         }
67 
68         return rez;
69     }
70 
71     // Get key and value of response
72     Pair getPair()
73     {
74         return Pair(this.getKey(), this.getValue());
75     }
76 
77    
78     // Get multi-value iterator of response
79     auto getMultiPair()
80     {
81         //return refRange(new MultiPair(this));
82         return MultiPair(this);
83     }
84 
85     
86     auto getMultiKey()
87     {
88         //return refRange(new MultiKey(this));
89         return MultiKey(this);
90     }
91 
92     
93     auto getMultiValue()
94     {
95         //return refRange(new MultiValue(this));
96         return MultiValue(this);
97     }
98 
99     auto getMultiBool()
100     {
101         return this.getMultiKey().map!`a == "OK"`;
102     }
103 
104     // Get single value of response
105     string getKey() // const
106     {
107         if(!_sock.isValid) {
108             return null;
109         }
110         return _sock.readLine().idup;
111     }
112 }