use std::collections::BTreeMap;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
#[non_exhaustive]
pub enum FilterOp {
#[default]
Eq,
Ne,
Gt,
Gte,
Lt,
Lte,
Regex,
}
impl FilterOp {
#[must_use]
pub fn suffix(self) -> Option<&'static str> {
Some(match self {
Self::Eq => return None,
Self::Ne => "ne",
Self::Gt => "gt",
Self::Gte => "gte",
Self::Lt => "lt",
Self::Lte => "lte",
Self::Regex => "regex",
})
}
#[must_use]
pub fn parameter_for(self, attribute: &str) -> String {
match self.suffix() {
Some(suffix) => format!("{attribute}.{suffix}"),
None => attribute.to_owned(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Query {
fields: Vec<String>,
filters: BTreeMap<String, Vec<String>>,
sort: Vec<String>,
offset: Option<usize>,
limit: Option<usize>,
after: Option<String>,
before: Option<String>,
json_path: Option<String>,
}
impl Query {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn fields<I, S>(mut self, fields: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.fields.extend(fields.into_iter().map(Into::into));
self
}
#[must_use]
pub fn filter(self, attribute: impl AsRef<str>, value: impl Into<String>) -> Self {
self.filter_op(attribute, FilterOp::Eq, value)
}
#[must_use]
pub fn filter_op(
mut self,
attribute: impl AsRef<str>,
op: FilterOp,
value: impl Into<String>,
) -> Self {
self.filters
.entry(op.parameter_for(attribute.as_ref()))
.or_default()
.push(value.into());
self
}
#[must_use]
pub fn filter_any<I, S>(mut self, attribute: impl AsRef<str>, values: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.filters
.entry(attribute.as_ref().to_owned())
.or_default()
.extend(values.into_iter().map(Into::into));
self
}
#[must_use]
pub fn sort(mut self, attribute: impl Into<String>) -> Self {
self.sort.push(attribute.into());
self
}
#[must_use]
pub fn offset(mut self, offset: usize) -> Self {
self.offset = Some(offset);
self
}
#[must_use]
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
#[must_use]
pub fn after(mut self, cursor: impl Into<String>) -> Self {
self.after = Some(cursor.into());
self
}
#[must_use]
pub fn before(mut self, cursor: impl Into<String>) -> Self {
self.before = Some(cursor.into());
self
}
#[must_use]
pub fn json_path(mut self, expression: impl Into<String>) -> Self {
self.json_path = Some(expression.into());
self
}
#[must_use]
pub fn limit_value(&self) -> Option<usize> {
self.limit
}
#[must_use]
pub fn offset_value(&self) -> Option<usize> {
self.offset
}
#[must_use]
pub fn to_params(&self) -> BTreeMap<String, String> {
let mut params: BTreeMap<String, String> = self
.filters
.iter()
.map(|(name, values)| (name.clone(), values.join(",")))
.collect();
if !self.fields.is_empty() {
params.insert("fields".to_owned(), self.fields.join(","));
}
if !self.sort.is_empty() {
params.insert("sort".to_owned(), self.sort.join(","));
}
if let Some(offset) = self.offset {
params.insert("offset".to_owned(), offset.to_string());
}
if let Some(limit) = self.limit {
params.insert("limit".to_owned(), limit.to_string());
}
if let Some(cursor) = &self.after {
params.insert("after".to_owned(), cursor.clone());
}
if let Some(cursor) = &self.before {
params.insert("before".to_owned(), cursor.clone());
}
if let Some(expression) = &self.json_path {
params.insert("filter".to_owned(), expression.clone());
}
params
}
#[must_use]
pub fn to_query_string(&self) -> String {
self.to_params()
.iter()
.map(|(k, v)| format!("{}={}", encode(k), encode(v)))
.collect::<Vec<_>>()
.join("&")
}
}
impl fmt::Display for Query {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_query_string())
}
}
fn encode(value: &str) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(byte as char);
}
_ => {
let _ = write!(out, "%{byte:02X}");
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn renders_params_in_stable_order() {
let a = Query::new().filter("b", "2").filter("a", "1").limit(5);
let b = Query::new().limit(5).filter("a", "1").filter("b", "2");
assert_eq!(a.to_query_string(), b.to_query_string());
assert_eq!(a.to_query_string(), "a=1&b=2&limit=5");
}
#[test]
fn encodes_reserved_characters() {
let q = Query::new().filter("name", "Basic Firewall & More");
assert_eq!(q.to_query_string(), "name=Basic%20Firewall%20%26%20More");
}
#[test]
fn joins_fields_and_sort() {
let q = Query::new().fields(["id", "name"]).sort("-name").sort("id");
let params = q.to_params();
assert_eq!(params["fields"], "id,name");
assert_eq!(params["sort"], "-name,id");
}
#[test]
fn a_repeated_attribute_widens_rather_than_replacing() {
let q = Query::new()
.filter("state", "held")
.filter("state", "pending");
assert_eq!(q.to_params()["state"], "held,pending");
}
#[test]
fn operators_render_as_a_suffix_on_the_attribute() {
let q = Query::new()
.filter_op("orderDate", FilterOp::Gte, "2026-01-01")
.filter_op("orderDate", FilterOp::Lt, "2027-01-01");
let params = q.to_params();
assert_eq!(params["orderDate.gte"], "2026-01-01");
assert_eq!(params["orderDate.lt"], "2027-01-01");
assert_eq!(params.len(), 2, "the two bounds must not collide");
}
#[test]
fn equality_needs_no_suffix() {
assert_eq!(FilterOp::Eq.parameter_for("state"), "state");
assert_eq!(FilterOp::Regex.parameter_for("name"), "name.regex");
}
#[test]
fn alternatives_render_as_one_comma_list() {
let q = Query::new().filter_any("state", ["acknowledged", "inProgress"]);
assert_eq!(q.to_params()["state"], "acknowledged,inProgress");
}
}