auric-runtime 0.1.3

Runtime for the Ember-inspired Auric SPA framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use super::{Adapter, FindAllOptions, FindOptions, QueryRecordOptions};
use anyhow::{Result, anyhow};
use jsonapi_core::{Resource, ResourceObject};
use pluralizer::pluralize;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

#[derive(Default)]
pub struct Store {
    adapters: HashMap<String, Arc<dyn Adapter + Send + Sync>>,
    cache: HashMap<String, HashMap<String, Resource>>,
}

impl Store {
    pub fn new(adapters: HashMap<String, Arc<dyn Adapter + Send + Sync>>) -> Self {
        Self {
            adapters,
            cache: HashMap::new(),
        }
    }

    /// Returns an instance of the adapter for the given model name
    pub fn adapter_for(&self, model_name: &str) -> Result<Arc<dyn Adapter>> {
        // Find an adapter for the model name
        if let Some(adapter) = self.adapters.get(model_name) {
            return Ok(adapter.clone());
        }

        // Default to an application adapter
        const APPLICATION: &str = "application";
        if model_name != APPLICATION
            && let Some(adapter) = self.adapters.get(APPLICATION)
        {
            return Ok(adapter.clone());
        }

        Err(anyhow!("No such adapter"))
    }

    /// Create a new record in the current store
    pub async fn create_record<M>(&self, model: M) -> Result<M>
    where
        M: ResourceObject,
    {
        let model_name = pluralize(model.resource_type(), 1, false);
        let adapter = self.adapter_for(&model_name)?;
        let attributes: Value = serde_json::to_value(&model)?;
        let resource = Resource {
            type_: model.resource_type().to_string(),
            id: model.resource_id().map(|id| id.to_string()),
            lid: None,
            attributes,
            relationships: Default::default(),
            links: None,
            meta: None,
        };
        let finalized_resource = adapter.create_record(resource).await?;
        let json = serde_json::to_string(&finalized_resource)?;
        let model: M = serde_json::from_str(&json)?;
        Ok(model)
    }

    /// Delete a record
    pub async fn delete_record<M>(&self, model: M) -> Result<()>
    where
        M: ResourceObject,
    {
        let model_name = pluralize(model.resource_type(), 1, false);
        let adapter = self.adapter_for(&model_name)?;
        let attributes: Value = serde_json::to_value(&model)?;
        let resource = Resource {
            type_: model.resource_type().to_string(),
            id: model.resource_id().map(|id| id.to_string()),
            lid: None,
            attributes,
            relationships: Default::default(),
            links: None,
            meta: None,
        };
        adapter.delete_record(&resource).await?;
        Ok(())
    }

    /// Find all the records for the given resource type
    pub async fn find_all<M>(&self, resource_type: &str, _options: Option<FindAllOptions>) -> Result<Vec<M>>
    where
        M: ResourceObject,
    {
        assert_eq!(resource_type, pluralize(resource_type, 1, false));
        let _adapter = self.adapter_for(resource_type)?;
        todo!("NIY")
    }

    /// Find a single record
    pub async fn find_record<M>(&self, resource_type: &str, id: &str, _options: Option<FindOptions>) -> Result<M>
    where
        M: ResourceObject,
    {
        assert_eq!(resource_type, pluralize(resource_type, 1, false));
        let adapter = self.adapter_for(resource_type)?;
        let collection = pluralize(resource_type, 2, false);
        let resource = adapter.find_record(&collection, id).await?;
        let json = serde_json::to_string(&resource)?;
        let model: M = serde_json::from_str(&json)?;
        Ok(model)
    }

    /// Check for a single record without triggering a fetch
    pub fn peek_record<M>(&self, resource_type: &str, id: &str) -> Result<Option<M>>
    where
        M: ResourceObject,
    {
        assert_eq!(resource_type, pluralize(resource_type, 1, false));
        let collection = pluralize(resource_type, 2, false);
        match self.cache.get(&collection) {
            None => Ok(None),
            Some(resources) => match resources.get(id) {
                None => Ok(None),
                Some(resource) => {
                    let json = serde_json::to_string(resource)?;
                    let model: M = serde_json::from_str(&json)?;
                    Ok(Some(model))
                }
            },
        }
    }

    /// Push a model into the store
    pub fn push<M>(&mut self, model: M) -> Result<()>
    where
        M: ResourceObject,
    {
        let collection = model.resource_type();
        let id = model.resource_id().unwrap_or_default().to_string();
        let json = serde_json::to_string(&model)?;
        let resource: Resource = serde_json::from_str(&json)?;
        match self.cache.get_mut(collection) {
            None => {
                self.cache
                    .insert(collection.to_string(), HashMap::from([(id, resource)]));
            }
            Some(map) => {
                map.insert(id, resource);
            }
        }
        Ok(())
    }

    /// Delegate a query to the adapter
    pub async fn query<M>(&self, resource_type: &str, _query: serde_json::Value) -> Result<Vec<M>>
    where
        M: ResourceObject,
    {
        assert_eq!(resource_type, pluralize(resource_type, 1, false));
        let _adapter = self.adapter_for(resource_type)?;
        todo!("NIY")
    }

    /// Delegate the request for a single record to the adapter
    pub async fn query_record<M>(
        &self,
        resource_type: &str,
        _query: serde_json::Value,
        _options: Option<QueryRecordOptions>,
    ) -> Result<Vec<M>>
    where
        M: ResourceObject,
    {
        assert_eq!(resource_type, pluralize(resource_type, 1, false));
        let _adapter = self.adapter_for(resource_type)?;
        todo!("NIY")
    }

    /// Unloads all records in the store for the given resource type
    pub fn unload_all(&mut self, resource_type: &str) -> Result<()> {
        assert_eq!(resource_type, pluralize(resource_type, 1, false));
        let collection = pluralize(resource_type, 2, false);
        if let Some(map) = self.cache.get_mut(&collection) {
            map.clear();
        }
        Ok(())
    }

    /// Unload a single record from the store
    pub fn unload_record<M>(&mut self, model: &M) -> Result<()>
    where
        M: ResourceObject,
    {
        let collection = model.resource_type();
        if let Some(map) = self.cache.get_mut(collection) {
            let id = model.resource_id().unwrap_or_default().to_string();
            map.remove(id.as_str());
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::Store;
    use crate::data::adapters::RestAdapter;
    use crate::data::{Adapter, QueryRecordOptions};
    use async_trait::async_trait;
    use httptest::matchers::request;
    use httptest::responders::{json_encoded, status_code};
    use httptest::{Expectation, Server};
    use jsonapi_core::{JsonApi, Resource};
    use serde_json::{Value, json};
    use std::collections::HashMap;
    use std::sync::Arc;

    #[derive(Clone, Debug, JsonApi, PartialEq)]
    #[jsonapi(type = "customers")]
    struct Customer {
        #[jsonapi(id)]
        id: String,
    }

    #[tokio::test]
    async fn cannot_peek_non_existing() {
        let store = Store::default();
        let maybe_customer = store.peek_record::<Customer>("customer", "123").unwrap();
        assert_eq!(maybe_customer, None);
    }

    #[tokio::test]
    async fn can_push_then_peek_record() {
        let mut store = Store::default();
        let customer = Customer { id: "123".to_string() };
        store.push(customer.clone()).unwrap();
        let maybe_customer = store.peek_record::<Customer>("customer", "123").unwrap();
        assert_eq!(maybe_customer, Some(customer));
    }

    #[tokio::test]
    async fn can_push_then_unload_all() {
        let mut store = Store::default();
        let customer = Customer { id: "123".to_string() };
        store.push(customer.clone()).unwrap();
        assert!(store.peek_record::<Customer>("customer", "123").unwrap().is_some());
        store.unload_all("customer").unwrap();
        assert!(store.peek_record::<Customer>("customer", "123").unwrap().is_none());
    }

    #[tokio::test]
    async fn can_push_then_unload_record() {
        let mut store = Store::default();
        let customer_1 = Customer { id: "123".to_string() };
        let customer_2 = Customer { id: "456".to_string() };
        store.push(customer_1.clone()).unwrap();
        store.push(customer_2.clone()).unwrap();
        assert!(store.peek_record::<Customer>("customer", "123").unwrap().is_some());
        assert!(store.peek_record::<Customer>("customer", "456").unwrap().is_some());
        store.unload_record(&customer_2).unwrap();
        assert!(store.peek_record::<Customer>("customer", "123").unwrap().is_some());
        assert!(store.peek_record::<Customer>("customer", "456").unwrap().is_none());
    }

    #[tokio::test]
    async fn cannot_find_non_existing_adapter() {
        let store = Store::default();
        let maybe_adapter = store.adapter_for("foo");
        assert!(maybe_adapter.is_err());
    }

    #[tokio::test]
    async fn can_find_adapter() {
        #[derive(Default)]
        struct FooAdapter {}
        #[async_trait(?Send)]
        impl Adapter for FooAdapter {
            async fn create_record(&self, _resource: Resource) -> anyhow::Result<Resource> {
                todo!()
            }
            async fn delete_record(&self, _resource: &Resource) -> anyhow::Result<()> {
                todo!()
            }
            async fn find_record(&self, _resource_type: &str, _id: &str) -> anyhow::Result<Resource> {
                todo!()
            }
            async fn query(&self, _resource_type: &str, _query: Value) -> anyhow::Result<Vec<Resource>> {
                todo!()
            }
            async fn query_record(
                &self,
                _resource_type: &str,
                _query: Value,
                _options: QueryRecordOptions,
            ) -> anyhow::Result<Resource> {
                todo!()
            }
            async fn update_record(&self, _resource: Resource) -> anyhow::Result<Resource> {
                todo!()
            }
        }
        const MODEL: &str = "foo";
        let adapter: Arc<dyn Adapter + Send + Sync> = Arc::new(FooAdapter::default());
        let adapters = HashMap::from([(MODEL.to_string(), adapter)]);
        let store = Store::new(adapters);
        let maybe_adapter = store.adapter_for(MODEL);
        assert!(maybe_adapter.is_ok());
    }

    #[tokio::test]
    async fn can_default_to_application_adapter() {
        #[derive(Default)]
        struct ApplicationAdapter {}
        #[async_trait(?Send)]
        impl Adapter for ApplicationAdapter {
            async fn create_record(&self, _resource: Resource) -> anyhow::Result<Resource> {
                todo!()
            }
            async fn delete_record(&self, _resource: &Resource) -> anyhow::Result<()> {
                todo!()
            }
            async fn find_record(&self, _resource_type: &str, _id: &str) -> anyhow::Result<Resource> {
                todo!()
            }
            async fn query(&self, _resource_type: &str, _query: Value) -> anyhow::Result<Vec<Resource>> {
                todo!()
            }
            async fn query_record(
                &self,
                _resource_type: &str,
                _query: Value,
                _options: QueryRecordOptions,
            ) -> anyhow::Result<Resource> {
                todo!()
            }
            async fn update_record(&self, _resource: Resource) -> anyhow::Result<Resource> {
                todo!()
            }
        }
        const MODEL: &str = "application";
        let adapter: Arc<dyn Adapter + Send + Sync> = Arc::new(ApplicationAdapter::default());
        let adapters = HashMap::from([(MODEL.to_string(), adapter)]);
        let store = Store::new(adapters);
        let maybe_adapter = store.adapter_for("foo");
        assert!(maybe_adapter.is_ok());
    }

    #[tokio::test]
    async fn can_create_record() {
        // Setup mock server and expections for a find Customer operation
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("POST", "/v1/customers")).respond_with(json_encoded(
                json!({"customer": {"id": "123", "name": "Acme Widgets 2"}}),
            )),
        );
        let server_url = server.url_str("/v1");

        #[derive(Clone, JsonApi)]
        #[jsonapi(type = "customers")]
        struct Customer {
            #[jsonapi(id)]
            id: String,
            name: String,
        }

        let adapter: Arc<dyn Adapter + Send + Sync> = Arc::new(RestAdapter::new(server_url));
        const MODEL: &str = "customer";
        let adapters = HashMap::from([(MODEL.to_string(), adapter)]);
        let store = Store::new(adapters);
        let _ = store.adapter_for(MODEL);
        let customer = Customer {
            id: String::new(),
            name: "Acme Widgets".to_string(),
        };
        let finalized_customer: Customer = store.create_record(customer.clone()).await.unwrap();
        assert_eq!(finalized_customer.id, "123".to_string());
        assert_eq!(finalized_customer.name, "Acme Widgets 2".to_string());
    }

    #[tokio::test]
    async fn can_delete_record() {
        // Setup mock server and expections for a find Customer operation
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("DELETE", "/v1/customers/123")).respond_with(status_code(200)),
        );
        let server_url = server.url_str("/v1");

        #[derive(Clone, JsonApi)]
        #[jsonapi(type = "customers")]
        struct Customer {
            #[jsonapi(id)]
            id: String,
            name: String,
        }

        let adapter: Arc<dyn Adapter + Send + Sync> = Arc::new(RestAdapter::new(server_url));
        const MODEL: &str = "customer";
        let adapters = HashMap::from([(MODEL.to_string(), adapter)]);
        let store = Store::new(adapters);
        let _ = store.adapter_for(MODEL);
        let customer = Customer {
            id: "123".to_string(),
            name: "Acme Widgets".to_string(),
        };
        store.delete_record(customer).await.unwrap();
    }

    #[tokio::test]
    async fn can_find_record() {
        // Setup mock server and expections for a find Customer operation
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("GET", "/v1/customers/123"))
                .respond_with(json_encoded(json!({"customer": {"id": "123", "name": "Acme Widgets"}}))),
        );
        let server_url = server.url_str("/v1");

        #[derive(Debug, JsonApi)]
        #[jsonapi(type = "customers")]
        struct Customer {
            #[jsonapi(id)]
            id: String,
            name: String,
        }

        let adapter: Arc<dyn Adapter + Send + Sync> = Arc::new(RestAdapter::new(server_url));
        const MODEL: &str = "customer";
        let adapters = HashMap::from([(MODEL.to_string(), adapter)]);
        let store = Store::new(adapters);
        let _ = store.adapter_for(MODEL);
        let customer: Customer = store.find_record(MODEL, "123", None).await.unwrap();
        assert_eq!(customer.id, "123".to_string());
        assert_eq!(customer.name, "Acme Widgets".to_string());
    }
}