1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.app.appcache;
7 
8 import diamond.http.client : HttpClient;
9 
10 /// Interface for an app cache.
11 interface IAppCache
12 {
13   /**
14   * Updates the app cache.
15   * Params:
16   *   client =        The client to cache from.
17   *   defaultResult = The default result to cache.
18   */
19   void updateCache(HttpClient client, string defaultResult);
20 
21   /**
22   * Retrieves the cached result based on a client.
23   * Params:
24   *   client = The client to receive the cached result based on.
25   * Returns:
26   *   The cached result.
27   */
28   string retrieveCache(HttpClient client);
29 
30   /// Clears the cache results.
31   void clearCache();
32 
33   /**
34   * Removes a cached result.
35   * Params:
36   *   client = The client to remove the cached result based on.
37   */
38   void removeCache(HttpClient client);
39 }
40 
41 /**
42 * Sets the app cache.
43 * Params:
44 *   cache = The app cache.
45 */
46 void setAppCache(IAppCache cache)
47 {
48   if (!cache)
49   {
50     return;
51   }
52 
53   _cache = cache;
54 }
55 
56 /// The cache.
57 private __gshared IAppCache _cache;
58 
59 package(diamond):
60 /// Wrapper around the default diamond app cache.
61 class DiamondAppCache : IAppCache
62 {
63   private:
64   /// The cache.
65   string[string] _cache;
66 
67   public:
68   /// Creates a new diamond app cache.
69   this()
70   {
71 
72   }
73 
74   /**
75   * Updates the app cache.
76   * Params:
77   *   client =        The client to cache from.
78   *   defaultResult = The default result to cache.
79   */
80   void updateCache(HttpClient client, string defaultResult)
81   {
82     _cache[client.route.name] = defaultResult;
83   }
84 
85   /**
86   * Retrieves the cached result based on a client.
87   * Params:
88   *   client = The client to receive the cached result based on.
89   * Returns:
90   *   The cached result.
91   */
92   string retrieveCache(HttpClient client)
93   {
94     return _cache.get(client.route.name, null);
95   }
96 
97   /// Clears the cache results.
98   void clearCache()
99   {
100     _cache.clear();
101   }
102 
103   /**
104   * Removes a cached result.
105   * Params:
106   *   client = The client to remove the cached result based on.
107   */
108   void removeCache(HttpClient client)
109   {
110     _cache.remove(client.route.name);
111   }
112 }
113 
114 /// Gets the app cache.
115 @property IAppCache cache()
116 {
117   return _cache;
118 }