Skip to content

Commit

Permalink
Update documentation. #6
Browse files Browse the repository at this point in the history
  • Loading branch information
gudaoxuri committed Mar 22, 2022
1 parent 1692dce commit c916e1e
Show file tree
Hide file tree
Showing 5 changed files with 154 additions and 10 deletions.
4 changes: 2 additions & 2 deletions examples/todos/src/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl TodoApi {
// curl -X POST "http://127.0.0.1:8089/todo" \
// -H "Accept: application/json" \
// -H "Content-Type: application/json" \
// -H "Tardis-Context: eyJhcHBfaWQiOiAiIiwidGVuYW50X2lkIjogIiIsImFrIjogIiIsImFjY291bnRfaWQiOiAiIiwidG9rZW4iOiAiIiwidG9rZW5fa2luZCI6ICIiLCJyb2xlcyI6IFtdLCJncm91cHMiOiBbXX0=" \
// -H "Tardis-Context: eyJhcHBfY29kZSI6ICIiLCJ0ZW5hbnRfY29kZSI6ICIiLCJhayI6ICIiLCJhY2NvdW50X2NvZGUiOiAiIiwidG9rZW4iOiAiIiwidG9rZW5fa2luZCI6ICIiLCJyb2xlcyI6IFtdLCJncm91cHMiOiBbXX0=" \
// -d '{"code":" 测试2 ","description":"AA","done":false}'
#[oai(path = "/", method = "post")]
async fn add(&self, todo_add_req: Json<TodoAddReq>, cxt: TardisContextExtractor) -> TardisApiResult<i32> {
Expand Down Expand Up @@ -107,7 +107,7 @@ impl TodoApi {

// curl -X PUT "http://localhost:8089/todo/1" \
// -H "Accept: application/json" \
// -H "Tardis-Context: eyJhcHBfaWQiOiAiIiwidGVuYW50X2lkIjogIiIsImFrIjogIiIsImFjY291bnRfaWQiOiAiIiwidG9rZW4iOiAiIiwidG9rZW5fa2luZCI6ICIiLCJyb2xlcyI6IFtdLCJncm91cHMiOiBbXX0=" \
// -H "Tardis-Context: eyJhcHBfY29kZSI6ICIiLCJ0ZW5hbnRfY29kZSI6ICIiLCJhayI6ICIiLCJhY2NvdW50X2NvZGUiOiAiIiwidG9rZW4iOiAiIiwidG9rZW5fa2luZCI6ICIiLCJyb2xlcyI6IFtdLCJncm91cHMiOiBbXX0=" \
// -H "Content-Type: application/json" \
// -d '{"description":"AAAAAAAA","done":false}'
#[oai(path = "/:id", method = "put")]
Expand Down
23 changes: 21 additions & 2 deletions src/cache/cache_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,36 @@ use crate::basic::error::TardisError;
use crate::basic::result::TardisResult;
use crate::log::info;

/// Distributed cache handle / 分布式缓存操作
///
/// Encapsulates common Redis operations.
///
/// 封装了Redis的常用操作.
///
/// # Steps to use / 使用步骤
///
/// 1. Create the cache configuration / 创建缓存配置, @see [CacheConfig](crate::basic::config::CacheConfig)
///
/// 4. Use `TardisCacheClient` to operate cache / 使用 `TardisCacheClient` 操作缓存, E.g:
/// ```rust
/// use tardis::TardisFuns;
/// assert_eq!(TardisFuns::cache().get("test_key").await.unwrap(), None);
/// client.set("test_key", "测试").await.unwrap();
/// assert_eq!(TardisFuns::cache().get("test_key").await.unwrap(), "测试");
/// assert!(TardisFuns::cache().set_nx("test_key2", "测试2").await.unwrap());
/// assert!(!TardisFuns::cache().set_nx("test_key2", "测试2").await.unwrap());
/// ```
pub struct TardisCacheClient {
con: Connection,
}

impl TardisCacheClient {
/// Initialize configuration from the cache configuration object / 从缓存配置对象中初始化配置
pub async fn init_by_conf(conf: &FrameworkConfig) -> TardisResult<TardisCacheClient> {
TardisCacheClient::init(&conf.cache.url).await
}

/// Initialize configuration / 初始化配置
pub async fn init(str_url: &str) -> TardisResult<TardisCacheClient> {
let url = Url::parse(str_url).unwrap_or_else(|_| panic!("[Tardis.CacheClient] Invalid url {}", str_url));
info!(
Expand All @@ -37,8 +58,6 @@ impl TardisCacheClient {
Ok(TardisCacheClient { con })
}

// basic operations

pub async fn set(&mut self, key: &str, value: &str) -> RedisResult<()> {
self.con.set(key, value).await
}
Expand Down
8 changes: 3 additions & 5 deletions src/db/reldb_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ use crate::{FrameworkConfig, TardisFuns};

/// Relational database handle / 关系型数据库操作
///
/// Provides some common regular, Id generation and other functions.
///
/// Encapsulates common operations on MySQL and PostgreSQL. Two styles of operations are provided:
/// Encapsulates common operations of MySQL and PostgreSQL. Two styles of operations are provided:
///
/// 1. Wrapper based on `sea-orm` for simple relational operations, see `examples/reldb` for examples
/// 1. Wrapper based on `sea-query` for complex, custom processing operations, see `https://github.com/ideal-world/bios` for examples.
Expand Down Expand Up @@ -457,8 +455,8 @@ impl<'a> TardisRelDBlConnection<'a> {
/// Create a table from an entity / 从实体中创建表
///
/// # Arguments
//
// * `entity` - entity / 实体
///
/// * `entity` - entity / 实体
///
/// # Examples
/// ```rust
Expand Down
38 changes: 37 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,6 @@ impl TardisFuns {
/// ```
/// 3. Call this function to complete various data processing operations / 调用本函数完成各种数据处理操作 E.g.
/// ```rust
/// use std::process::id;
/// use tardis::basic::error::TardisError;
/// use tardis::TardisFuns;
/// use tardis::db::sea_orm::*;
Expand Down Expand Up @@ -589,6 +588,25 @@ impl TardisFuns {
}
}

/// Use the distributed cache feature / 使用分布式缓存功能
///
/// This feature needs to be enabled #[cfg(feature = "cache")] .
///
/// 本功能需要启用 #[cfg(feature = "cache")] .
///
/// # Steps to use / 使用步骤
///
/// 1. Initialize the cache configuration / 初始化缓存配置 @see [init](Self::init)
/// 2. Call this function to complete various cache processing operations / 调用本函数完成各种缓存处理操作
/// E.g.
/// ```rust
/// use tardis::TardisFuns;
/// assert_eq!(TardisFuns::cache().get("test_key").await.unwrap(), None);
/// client.set("test_key", "测试").await.unwrap();
/// assert_eq!(TardisFuns::cache().get("test_key").await.unwrap(), "测试");
/// assert!(TardisFuns::cache().set_nx("test_key2", "测试2").await.unwrap());
/// assert!(!TardisFuns::cache().set_nx("test_key2", "测试2").await.unwrap());
/// ```
#[cfg(feature = "cache")]
pub fn cache() -> &'static mut TardisCacheClient {
unsafe {
Expand All @@ -609,6 +627,24 @@ impl TardisFuns {
}
}

/// Use the distributed search feature / 使用分布式搜索功能
///
/// This feature needs to be enabled #[cfg(feature = "web-client")] .
///
/// 本功能需要启用 #[cfg(feature = "web-client")] .
///
/// # Steps to use / 使用步骤
///
/// 1. Initialize the web client configuration / 初始化web客户端配置 @see [init](Self::init)
/// 2. Call this function to complete various search processing operations / 调用本函数完成各种搜索处理操作
/// E.g.
/// ```rust
/// use tardis::TardisFuns;
/// TardisFuns::search().create_index("test_index").await.unwrap();
/// let id = TardisFuns::search().create_record("test_index", r#"{"user":{"id":1,"name":"张三","open":false}}"#).await.unwrap();
/// assert_eq!(TardisFuns::search().get_record("test_index", &id).await.unwrap(), r#"{"user":{"id":4,"name":"Tom","open":true}}"#);
/// TardisFuns::search().simple_search("test_index", "张三").await.unwrap();
/// ```
#[cfg(feature = "web-client")]
pub fn search() -> &'static TardisSearchClient {
unsafe {
Expand Down
91 changes: 91 additions & 0 deletions src/search/search_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,36 @@ use crate::basic::result::TardisResult;
use crate::log::{debug, info};
use crate::{FrameworkConfig, TardisFuns, TardisWebClient};

/// Distributed search handle / 分布式搜索操作
///
/// Encapsulates common elasticsearch operations.
///
/// 封装了Elasticsearch的常用操作.
///
/// # Steps to use / 使用步骤
///
/// 1. Create the search configuration / 创建搜索配置, @see [SearchConfig](crate::basic::config::SearchConfig)
///
/// 2. Use `TardisSearchClient` to operate search / 使用 `TardisSearchClient` 操作搜索, E.g:
/// ```rust
/// use tardis::TardisFuns;
/// TardisFuns::search().create_index("test_index").await.unwrap();
/// let id = TardisFuns::search().create_record("test_index", r#"{"user":{"id":1,"name":"张三","open":false}}"#).await.unwrap();
/// assert_eq!(TardisFuns::search().get_record("test_index", &id).await.unwrap(), r#"{"user":{"id":4,"name":"Tom","open":true}}"#);
/// TardisFuns::search().simple_search("test_index", "张三").await.unwrap();
/// ```
pub struct TardisSearchClient {
client: TardisWebClient,
server_url: String,
}

impl TardisSearchClient {
/// Initialize configuration from the search configuration object / 从搜索配置对象中初始化配置
pub fn init_by_conf(conf: &FrameworkConfig) -> TardisResult<TardisSearchClient> {
TardisSearchClient::init(&conf.search.url, conf.search.timeout_sec)
}

/// Initialize configuration / 初始化配置
pub fn init(str_url: &str, timeout_sec: u64) -> TardisResult<TardisSearchClient> {
info!("[Tardis.SearchClient] Initializing");
let mut client = TardisWebClient::init(timeout_sec)?;
Expand All @@ -26,6 +46,17 @@ impl TardisSearchClient {
})
}

/// Create index / 创建索引
///
/// # Arguments
///
/// * `index_name` - index name / 索引名称
///
/// # Examples
/// ```rust
/// use tardis::TardisFuns;
/// TardisFuns::search().create_index("test_index").await.unwrap();
/// ```
pub async fn create_index(&self, index_name: &str) -> TardisResult<()> {
info!("[Tardis.SearchClient] Create index {}", index_name);
let url = format!("{}/{}", self.server_url, index_name);
Expand All @@ -37,6 +68,18 @@ impl TardisSearchClient {
}
}

/// Create record and return primary key value / 创建记录并返回主键值
///
/// # Arguments
///
/// * `index_name` - index name / 索引名称
/// * `data` - record content / 记录内容
///
/// # Examples
/// ```rust
/// use tardis::TardisFuns;
/// let id = TardisFuns::search().create_record("test_index", r#"{"user":{"id":1,"name":"张三","open":false}}"#).await.unwrap();
/// ```
pub async fn create_record(&self, index_name: &str, data: &str) -> TardisResult<String> {
debug!("[Tardis.SearchClient] Create index {}", index_name);
let url = format!("{}/{}/_doc/", self.server_url, index_name);
Expand All @@ -49,6 +92,18 @@ impl TardisSearchClient {
}
}

/// Get a record / 获取一条记录
///
/// # Arguments
///
/// * `index_name` - index name / 索引名称
/// * `id` - record primary key value / 记录主键值
///
/// # Examples
/// ```rust
/// use tardis::TardisFuns;
/// TardisFuns::search().get_record("test_index", "xxxx").await.unwrap();
/// ```
pub async fn get_record(&self, index_name: &str, id: &str) -> TardisResult<String> {
let url = format!("{}/{}/_doc/{}", self.server_url, index_name, id);
let resp = self.client.get_to_str(&url, None).await?;
Expand All @@ -60,6 +115,18 @@ impl TardisSearchClient {
}
}

/// Simple (global) search / 简单(全局)搜索
///
/// # Arguments
///
/// * `index_name` - index name / 索引名称
/// * `q` - keyword / 搜索关键字
///
/// # Examples
/// ```rust
/// use tardis::TardisFuns;
/// TardisFuns::search().simple_search("test_index", "张三").await.unwrap();
/// ```
pub async fn simple_search(&self, index_name: &str, q: &str) -> TardisResult<Vec<String>> {
let url = format!("{}/{}/_search?q={}", self.server_url, index_name, q);
let resp = self.client.get_to_str(&url, None).await?;
Expand All @@ -70,12 +137,36 @@ impl TardisSearchClient {
}
}

/// Specified fields search / 指定字段搜索
///
/// # Arguments
///
/// * `index_name` - index name / 索引名称
/// * `q` - search fields / 搜索的字段集合
///
/// The format of the search field: key = field name , value = field value, exact match, key supports multi-level operations of Json.
///
/// 搜索字段的格式: key = 字段名 , value = 字段值,精确匹配,key支持Json的多级操作.
///
/// # Examples
/// ```rust
/// use std::collections::HashMap;
/// use tardis::TardisFuns;
/// TardisFuns::search().multi_search(index_name, HashMap::from([("user.id", "1"), ("user.name", "李四")])).await.unwrap();
/// ```
pub async fn multi_search(&self, index_name: &str, q: HashMap<&str, &str>) -> TardisResult<Vec<String>> {
let q = q.into_iter().map(|(k, v)| format!(r#"{{"match": {{"{}": "{}"}}}}"#, k, v)).collect::<Vec<String>>().join(",");
let q = format!(r#"{{ "query": {{ "bool": {{ "must": [{}]}}}}}}"#, q);
self.raw_search(index_name, &q).await
}

/// Search using native format / 使用原生格式搜索
///
/// # Arguments
///
/// * `index_name` - index name / 索引名称
/// * `q` - native format / 原生格式
///
pub async fn raw_search(&self, index_name: &str, q: &str) -> TardisResult<Vec<String>> {
let url = format!("{}/{}/_search", self.server_url, index_name);
let resp = self.client.post_str_to_str(&url, q, None).await?;
Expand Down

0 comments on commit c916e1e

Please sign in to comment.