Documentation

req_

use std::{any::TypeId, future::Future};

use aok::Result;
use dashmap::DashMap;
use http::header::HeaderMap;
use tokio::sync::OnceCell;

pub trait Extract {
  fn id(headers: &HeaderMap) -> impl Future<Output = Result<u64>> + Send;
  fn new(id: u64) -> Self;
}

pub struct Req {
  pub headers: HeaderMap,
  pub cache: DashMap<TypeId, OnceCell<u64>>,
}

impl Req {
  pub fn new(headers: HeaderMap) -> Self {
    Self {
      headers,
      cache: DashMap::new(),
    }
  }

  pub async fn get<T: Extract + 'static>(&self) -> Result<T> {
    let type_id = TypeId::of::<T>();
    let cell = self.cache.entry(type_id).or_default();
    Ok(T::new(
      *cell.get_or_try_init(|| T::id(&self.headers)).await?,
    ))
  }
}

About

This project is an open-source component of i18n.site ⋅ Internationalization Solution.

关于

本项目为 i18n.site ⋅ 国际化解决方案 的开源组件。