Skip to content
Snippets Groups Projects
cache.rs 1.2 KiB
Newer Older
Hugo Trentesaux's avatar
Hugo Trentesaux committed
use crate::indexer::*;
use crate::*;

use anyhow::{anyhow, Result};
use std::collections::{hash_map, HashMap};

Hugo Trentesaux's avatar
Hugo Trentesaux committed
pub struct IdentityCache {
	client: Client,
	identities: HashMap<u32, String>,
Hugo Trentesaux's avatar
Hugo Trentesaux committed
	indexer: Option<Indexer>,
Hugo Trentesaux's avatar
Hugo Trentesaux committed
impl IdentityCache {
	pub fn new(client: Client, indexer: Option<Indexer>) -> Self {
		Self {
			client,
			identities: HashMap::new(),
			indexer,
		}
	}
	pub async fn fetch_identity(
		&mut self,
		identity_id: u32,
		parent_hash: sp_core::H256,
	) -> Result<String> {
		Ok(match self.identities.entry(identity_id) {
			hash_map::Entry::Occupied(entry) => entry.get().clone(),
			hash_map::Entry::Vacant(entry) => entry
				.insert({
					let pubkey = self
						.client
						.storage()
						.fetch(
Hugo Trentesaux's avatar
Hugo Trentesaux committed
							&runtime::storage().identity().identities(identity_id),
							Some(parent_hash),
						)
						.await?
						.ok_or_else(|| anyhow!("Identity {} not found", identity_id))?
						.owner_key
						.to_string();
					format!(
						"“ {} ”",
						if let Some(indexer) = &self.indexer {
							if let Ok(Some(username)) = indexer.username_by_pubkey(&pubkey).await {
								username
							} else {
								pubkey
							}
						} else {
							pubkey
						}
					)
				})
				.clone(),
		})
	}