Skip to main content

edc_web_components/contexts/
edc_identity_hub_context.rs

1use edc_identity_hub_client::{IdentityHubClient, IdentityHubClientVersion};
2use yew::prelude::*;
3use yew_oauth2::context::LatestAccessToken;
4use yew_oauth2::prelude::use_latest_access_token;
5
6#[derive(Clone, PartialEq)]
7pub struct EdcIdentityHubState {
8  participant_id: String,
9  participant_did: String,
10  latest_access_token_context: LatestAccessToken,
11}
12
13impl EdcIdentityHubState {
14  pub fn get_client(&self) -> IdentityHubClient {
15    let client = reqwest::Client::new();
16
17    let server_url = web_sys::window().unwrap().location().origin().unwrap();
18
19    IdentityHubClient::new(
20      client,
21      format!("{server_url}/identity-hub"),
22      self.latest_access_token_context.access_token(),
23      IdentityHubClientVersion::V1Alpha,
24    )
25  }
26
27  pub fn participant_id(&self) -> &str {
28    &self.participant_id
29  }
30  pub fn participant_did(&self) -> &str {
31    &self.participant_did
32  }
33}
34
35#[derive(Properties, PartialEq)]
36pub struct EdcIdentityHubContextProviderProps {
37  #[prop_or_default]
38  pub children: Html,
39  pub participant_id: String,
40  pub participant_did: String,
41}
42
43#[component]
44pub fn EdcIdentityHubContextProvider(props: &EdcIdentityHubContextProviderProps) -> Html {
45  let latest_access_token_context = use_latest_access_token().unwrap();
46
47  let edc_identity_hub_context = {
48    let latest_access_token_context = latest_access_token_context.clone();
49
50    use_state(move || EdcIdentityHubState {
51      participant_id: props.participant_id.clone(),
52      participant_did: props.participant_did.clone(),
53      latest_access_token_context,
54    })
55  };
56
57  use_effect_with(
58    (
59      props.participant_id.clone(),
60      props.participant_did.clone(),
61      edc_identity_hub_context.setter(),
62      latest_access_token_context.clone(),
63    ),
64    |(
65      participant_id,
66      participant_did,
67      edc_identity_hub_context_setter,
68      latest_access_token_context,
69    )| {
70      edc_identity_hub_context_setter.set(EdcIdentityHubState {
71        participant_id: participant_id.clone(),
72        participant_did: participant_did.clone(),
73        latest_access_token_context: latest_access_token_context.clone(),
74      });
75    },
76  );
77
78  html! {
79    <ContextProvider<EdcIdentityHubState> context={(*edc_identity_hub_context).clone()}>
80      { props.children.clone() }
81    </ContextProvider<EdcIdentityHubState>>
82  }
83}
84
85#[hook]
86pub fn use_edc_identity_hub_context() -> EdcIdentityHubState {
87  use_context::<EdcIdentityHubState>().expect("no EDC Identity Hub context found")
88}