graphql_federated_graph/federated_graph/
view.rs

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
//! Convenient methods and helper types to navigate a [FederatedGraph].

use std::ops::{Deref, Index};

use super::{FederatedGraph, StringId};

pub struct View<Id, Record> {
    pub(super) id: Id,
    pub(super) record: Record,
}

impl<Id, Record> View<Id, Record>
where
    Id: Copy,
{
    pub fn id(&self) -> Id {
        self.id
    }
}

impl<Id, Record> AsRef<Record> for View<Id, Record> {
    fn as_ref(&self) -> &Record {
        &self.record
    }
}

impl<Id, Record> std::ops::Deref for View<Id, Record> {
    type Target = Record;

    fn deref(&self) -> &Self::Target {
        &self.record
    }
}

pub struct ViewNested<'a, Id, Record> {
    pub(super) graph: &'a FederatedGraph,
    pub(super) view: View<Id, &'a Record>,
}

impl<'a, Id, Record> Deref for ViewNested<'a, Id, Record> {
    type Target = View<Id, &'a Record>;

    fn deref(&self) -> &Self::Target {
        &self.view
    }
}

impl<'a, Id, Record> AsRef<View<Id, &'a Record>> for ViewNested<'a, Id, Record> {
    fn as_ref(&self) -> &View<Id, &'a Record> {
        &self.view
    }
}

impl<Id, Record> AsRef<Record> for ViewNested<'_, Id, Record> {
    fn as_ref(&self) -> &Record {
        self.view.as_ref()
    }
}

impl<'a, Id, Record> ViewNested<'a, Id, Record> {
    /// Continue navigating with the next ID.
    pub fn then<NextId, NextRecord>(&self, next: impl FnOnce(&Record) -> NextId) -> ViewNested<'a, NextId, NextRecord>
    where
        NextId: Copy,
        FederatedGraph: Index<NextId, Output = NextRecord>,
    {
        self.graph.at(next(self.view.record))
    }
}

impl FederatedGraph {
    /// Start navigating the graph from the given ID. Returns a [ViewNested] that exposes further steps.
    pub fn at<Id, Record>(&self, id: Id) -> ViewNested<'_, Id, Record>
    where
        Id: Copy,
        FederatedGraph: Index<Id, Output = Record>,
    {
        ViewNested {
            graph: self,
            view: self.view(id),
        }
    }

    /// Resolve a [StringId].
    pub fn str(&self, id: StringId) -> &str {
        self[id].as_str()
    }

    /// View the record with the given ID.
    pub fn view<Id, Record>(&self, id: Id) -> View<Id, &Record>
    where
        Id: Copy,
        FederatedGraph: Index<Id, Output = Record>,
    {
        View { id, record: &self[id] }
    }
}