1 /*
2 * Hunt - A redis client library for D programming language.
3 *
4 * Copyright (C) 2018-2019 HuntLabs
5 *
6 * Website: https://www.huntlabs.net/
7 *
8 * Licensed under the Apache-2.0 License.
9 *
10 */
11
12 module hunt.redis.Response;
13
14 import hunt.redis.Builder;
15 import hunt.redis.Exceptions;
16
17 abstract class AbstractResponse {
18 protected AbstractResponse dependency = null;
19 protected bool building = false;
20 protected bool built = false;
21 protected bool _set = false;
22
23 protected RedisDataException exception = null;
24 protected Object data;
25
26 protected void build();
27
28 void set(Object data) {
29 this.data = data;
30 _set = true;
31 }
32
33 void setDependency(AbstractResponse dependency) {
34 this.dependency = dependency;
35 }
36
37 }
38
39 alias Response = RedisResponse;
40
41 class RedisResponse(T) : AbstractResponse {
42 protected T response = null;
43
44 private Builder!(T) builder;
45
46 this(Builder!(T) b) {
47 this.builder = b;
48 }
49
50 T get() {
51 // if response has dependency response and dependency is not built,
52 // build it first and no more!!
53 if (dependency !is null && dependency._set && !dependency.built) {
54 dependency.build();
55 }
56 if (!_set) {
57 throw new RedisDataException(
58 "Please close pipeline or multi block before calling this method.");
59 }
60 if (!built) {
61 build();
62 }
63 if (exception !is null) {
64 throw exception;
65 }
66 return response;
67 }
68
69 override protected void build() {
70 // check build state to prevent recursion
71 if (building) {
72 return;
73 }
74
75 building = true;
76 try {
77 if (data !is null) {
78 exception = cast(RedisDataException) data;
79 if (exception is null) {
80 response = builder.build(data);
81 }
82 }
83
84 data = null;
85 } finally {
86 building = false;
87 built = true;
88 }
89 }
90
91 override
92 string toString() {
93 return "Response " ~ builder.toString();
94 }
95
96 }