Introduce the criteria update setting

This commit is contained in:
Clément Renault
2020-12-04 12:02:22 +01:00
parent f8f33d35e0
commit 61b383f422
7 changed files with 181 additions and 34 deletions

View File

@ -1,5 +1,7 @@
use crate::FieldId;
use crate::{FieldsIdsMap, FieldId};
use anyhow::{Context, bail};
use regex::Regex;
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq, Eq)]
@ -24,6 +26,38 @@ pub enum Criterion {
Desc(FieldId),
}
impl Criterion {
pub fn from_str(fields_ids_map: &mut FieldsIdsMap, txt: &str) -> anyhow::Result<Criterion> {
match txt {
"typo" => Ok(Criterion::Typo),
"words" => Ok(Criterion::Words),
"proximity" => Ok(Criterion::Proximity),
"attribute" => Ok(Criterion::Attribute),
"wordsposition" => Ok(Criterion::WordsPosition),
"exactness" => Ok(Criterion::Exactness),
text => {
let re = Regex::new(r#"(asc|desc)\(([\w_-]+)\)"#)?;
let caps = re.captures(text).with_context(|| format!("unknown criterion name: {}", text))?;
let order = caps.get(1).unwrap().as_str();
let field_name = caps.get(2).unwrap().as_str();
let field_id = fields_ids_map.insert(field_name).context("field id limit reached")?;
match order {
"asc" => Ok(Criterion::Asc(field_id)),
"desc" => Ok(Criterion::Desc(field_id)),
otherwise => bail!("unknown criterion name: {}", otherwise),
}
},
}
}
pub fn field_id(&self) -> Option<FieldId> {
match *self {
Criterion::Asc(fid) | Criterion::Desc(fid) => Some(fid),
_ => None,
}
}
}
pub fn default_criteria() -> Vec<Criterion> {
vec![
Criterion::Typo,