Skip to content

Fluent schema builder

LateApexEarlySpeed edited this page Apr 22, 2024 · 3 revisions

Intro

If not familiar with Standard Json schema, recommend using fluent configuration. The fluent configuration is designed not completely align with standard Json schema keywords interface. The standard Json schema is a powerful and flexiable language to specify json shape, but most developers may be more familiar with "stronger type" smell. For this, library's fluent configuration will (in most cases) firstly "ask" developers what json type they want, then continue "ask" subsequence validation requirements which are scoped based on known json type.

By doing that, developers may have more friendly method invoke chains and will not be easy to make mistake because some standard json schema keywords only have functionalities on specific type. Also, because validation methods is on specific json type builder, so those validation methods can be designed to accept concret .net type rather than raw json.

    var b = new JsonSchemaBuilder();
    b.ObjectHasProperty("A", b => b.IsJsonString().HasMinLength(5))
    .HasProperty("B", b => b.IsJsonNumber().IsGreaterThan(1).IsLessThan(10))
    .HasProperty("C", b => b.IsJsonArray().HasMinLength(5).HasItems(b =>
    {
        b.NotJsonNull();
    }))
    .HasProperty("D", b => b.Or(
        b => b.IsJsonFalse(),
        b => b.IsJsonNumber().Equal(0),
        b => b.IsJsonObject().HasCustomValidation((JsonElement element) => element.GetProperty("Prop").ValueKind == JsonValueKind.True, 
            jsonElement => $"Cannot pass my custom validation, data is {jsonElement}")
      )
    );
    JsonValidator jsonValidator = b.BuildValidator();
    jsonValidator.Validate(...);

Available fluent validation methods

  • NotJsonNull
  • IsJsonTrue
  • IsJsonFalse
  • IsJsonBoolean
  • IsJsonNull
  • IsJsonString:
    • Equal
    • IsIn
    • HasMaxLength
    • HasMinLength
    • HasPattern
    • HasCustomValidation
  • StringEqual
  • StringHasPattern
  • IsJsonNumber:
    • Equal
    • IsIn
    • IsGreaterThan
    • IsLessThan
    • NotGreaterThan
    • NotLessThan
    • MultipleOf
    • HasCustomValidation
  • IsJsonArray:
    • SerializationEquivalent
    • HasItems
    • HasLength
    • HasMaxLength
    • HasMinLength
    • HasUniqueItems
    • HasCustomValidation
    • Contains
    • NotContains
    • Equivalent
  • ArrayHasItems
  • ArrayContains
  • IsJsonObject:
    • SerializationEquivalent
    • HasProperty
    • HasCustomValidation
    • Equivalent
    • HasNoProperty
  • ObjectHasProperty
  • Or

There are HasCustomValidation() overloads which can be used to create custom validation logic unit.