From 4f0a12d44cde3f7ac6acbf6dc533019d5365fde7 Mon Sep 17 00:00:00 2001 From: Maaz Ahmed <maaz.a@subcom.tech> Date: Mon, 12 Feb 2024 11:44:16 +0530 Subject: [PATCH] refactor: move type name inference to a dedicated function --- src/lib.rs | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 85d53af..5f709e7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,34 +1,38 @@ -use std::{fmt::Display, marker::PhantomData}; +use std::fmt::Display; use jsonschema::{Draft, JSONSchema}; use serde_json::{Map, Value}; -pub struct Inspector<T> { +pub struct Inspector { schema: JSONSchema, - marker: PhantomData<T>, } -impl<T> Inspector<T> { +impl Inspector { const PROP: &'static str = "properties"; const REF: &'static str = "$ref"; const AOF: &'static str = "allOf"; + /// Initialize an Inspector using the name of the type provided to the function using the turbofish syntax + pub fn new_infer<T>(schemas: &Value, resolve_refs: bool) -> Result<Self, InitError> { + // get target name from type inference + let target = std::any::type_name::<T>() + .split("::") + .last() + .ok_or(InitError::UnknownFailure)?; + Self::new(target, schemas, resolve_refs) + } + /// Construct an instance of a schema `Inspector` using the provided OpenAPI spec's schemas (in the form of `serde_json::Value`) - pub fn new(schemas: &Value, resolve_refs: bool) -> Result<Self, InitError> { + pub fn new(target: &str, schemas: &Value, resolve_refs: bool) -> Result<Self, InitError> { use InitError::*; // extract schemas object let Value::Object(schemas) = schemas else { return Err(InitError::UnknownFailure); }; - // get target name from type inference - let target_name = std::any::type_name::<T>() - .split("::") - .last() - .ok_or(UnknownFailure)?; // extract target from schema let Value::Object(mut target) = schemas - .get(target_name) - .ok_or(SchemaNotFound(target_name))? + .get(target) + .ok_or_else(|| SchemaNotFound(target.to_owned()))? .to_owned() else { return Err(InitError::UnknownFailure); @@ -48,7 +52,6 @@ impl<T> Inspector<T> { .compile(&Value::Object(target)) .ok() .ok_err()?, - marker: PhantomData, }) } @@ -126,7 +129,7 @@ impl Display for SchemaError { #[derive(Debug)] pub enum InitError { - SchemaNotFound(&'static str), + SchemaNotFound(String), ResolutionFailure(String), CompileFailure, UnknownFailure, -- GitLab