Skip to content
Snippets Groups Projects
Commit 4f0a12d4 authored by Maaz Ahmed's avatar Maaz Ahmed
Browse files

refactor: move type name inference to a dedicated function

parent 02b075e5
No related branches found
No related tags found
No related merge requests found
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,
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment