use async_graphql::Error as GqlError;
use crate::errors::gql_bad_request;
pub fn parse_gql_id(id: &str) -> Result<i64, GqlError> {
id.parse::<i64>()
.map_err(|_| gql_bad_request(format!("Invalid ID: {}", id)))
}
pub fn parse_gql_id_field(id: &str, field: &str) -> Result<i64, GqlError> {
id.parse::<i64>()
.map_err(|_| gql_bad_request(format!("Invalid {}: {}", field, id)))
}
#[macro_export]
macro_rules! gql_id {
($id:expr) => {
$crate::graphql::helpers::parse_gql_id($id)?
};
($id:expr, $field:expr) => {
$crate::graphql::helpers::parse_gql_id_field($id, $field)?
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_gql_id_valid() {
assert_eq!(parse_gql_id("123").unwrap(), 123);
assert_eq!(parse_gql_id("0").unwrap(), 0);
assert_eq!(parse_gql_id("-1").unwrap(), -1);
}
#[test]
fn test_parse_gql_id_invalid() {
assert!(parse_gql_id("abc").is_err());
assert!(parse_gql_id("").is_err());
assert!(parse_gql_id("12.34").is_err());
}
#[test]
fn test_parse_gql_id_field_valid() {
assert_eq!(parse_gql_id_field("42", "user_id").unwrap(), 42);
}
#[test]
fn test_parse_gql_id_field_invalid() {
let err = parse_gql_id_field("abc", "user_id").unwrap_err();
assert!(err.message.contains("user_id"));
}
}