diff --git a/README.md b/README.md index 1118822..a4c5a16 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ schemas then do not match the JSON that FSharp.SystemTextJson writes. This package adds schema and document transformers that read your `JsonFSharpOptions` and describe the real JSON: -- `option` and `voption`: the inner value, and `null` for `option` record +- `option` and `voption`: the inner value, and `null` for record and union fields - records: required and optional properties, including `Skippable<'T>` fields - unions: tags, internal, adjacent and external encodings, named fields, diff --git a/skills/fsharp-systemtextjson-openapi/SKILL.md b/skills/fsharp-systemtextjson-openapi/SKILL.md index 0247d47..619649d 100644 --- a/skills/fsharp-systemtextjson-openapi/SKILL.md +++ b/skills/fsharp-systemtextjson-openapi/SKILL.md @@ -67,8 +67,9 @@ reads. ## What the schema shows -- `option` record field: the inner schema plus `null`. Top-level `option` and - every `voption`: the inner schema only. +- `option` or `voption` record or union field: the inner schema plus `null`, + because `None` and `ValueNone` are written as `null`. Top-level `option` and + `voption`: the inner schema only. - With `UnwrapOption` turned off: `option` is `null` or a tagged `Some` object; `voption` is a tagged `ValueSome` or `ValueNone` object. - Records: a `Skippable<'T>` field is optional. With diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs index 81406ad..fcd20d3 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs @@ -10,6 +10,16 @@ open Microsoft.OpenApi module internal OpenApiSchemaHelpers = + let (|OptionOrValueOptionType|_|) (t: Type) = + if + t.IsGenericType + && (t.GetGenericTypeDefinition() = typedefof> + || t.GetGenericTypeDefinition() = typedefof>) + then + Some(t.GetGenericArguments()[0]) + else + None + let private hasSchemaTypeFlag (schemaType: JsonSchemaType) (flag: JsonSchemaType) = ((int schemaType) &&& (int flag)) = int flag diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Option.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Option.fs index 7ddc0ee..2bc8532 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Option.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Option.fs @@ -70,7 +70,7 @@ type OptionSchemaTransformer(fsOptions: JsonFSharpOptions) = let! innerSchema = getOrCreateSchema innerType SchemaCopy.copyTo schema innerSchema - // Top-level option schemas are unwrapped, while option-valued record properties remain nullable. + // Top-level option and voption schemas are unwrapped, while option- and voption-valued record properties remain nullable. if not (isNull ctx.JsonPropertyInfo) then OpenApiSchemaHelpers.addNull schema innerSchema } @@ -142,21 +142,12 @@ type OptionSchemaTransformer(fsOptions: JsonFSharpOptions) = } :> Task - let transformUnwrappedValueOption innerType = - task { - // ValueOption<'T> is erased to 'T' in schemas without adding property nullability. - let! innerSchema = getOrCreateSchema innerType - SchemaCopy.copyTo schema innerSchema - } - :> Task - match ctx.JsonTypeInfo.Type with - | Helpers.FSharpOptionType innerType when fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption -> + | Helpers.FSharpOptionType innerType + | Helpers.FSharpValueOptionType innerType when fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption -> transformUnwrappedOption innerType | Helpers.FSharpOptionType innerType -> transformWrappedOption innerType - | Helpers.FSharpValueOptionType innerType when fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption -> - transformUnwrappedValueOption innerType | Helpers.FSharpValueOptionType innerType -> transformWrappedValueOption innerType | _ -> diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs index 8461214..6bbccb1 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs @@ -21,12 +21,6 @@ module private RecordHelpers = else None - let (|FSharpOptionType|_|) (t: Type) = - if t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> then - Some(t.GetGenericArguments()[0]) - else - None - let getRecordProperties (fsOptions: JsonFSharpOptions) (recordType: Type) = let fields = FSharpType.GetRecordFields(recordType, true) @@ -54,6 +48,8 @@ module private RecordHelpers = type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = + let unwrapOptionFields = fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption + interface IOpenApiSchemaTransformer with member _.TransformAsync (schema: OpenApiSchema, ctx: OpenApiSchemaTransformerContext, ct: CancellationToken) @@ -104,9 +100,7 @@ type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = let propertySchemaTask = match effectiveType with - | RecordHelpers.FSharpOptionType innerType when - fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption - -> + | OpenApiSchemaHelpers.OptionOrValueOptionType innerType when unwrapOptionFields -> task { let! innerSchema = getOrCreateSchema innerType diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj b/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj index 4124ea7..3c897e8 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj @@ -1,7 +1,7 @@ SelectView.FSharp.SystemTextJson.OpenApi - 0.1.0 + 0.1.1 SelectView Copyright (c) SelectView OpenAPI schemas for F# types serialized with FSharp.SystemTextJson. Schema and document transformers for Microsoft.AspNetCore.OpenApi that cover options, records, unions, tuples, enums and collections. diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs index 52cdee5..fc48143 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs @@ -13,12 +13,6 @@ open Microsoft.OpenApi module private UnionHelpers = - let (|FSharpOptionType|_|) (t: Type) = - if t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> then - Some(t.GetGenericArguments()[0]) - else - None - let isFSharpOptionType (t: Type) = t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> @@ -160,6 +154,8 @@ module private UnionCasePromotionPlan = | NonNull metadata -> metadata.Remove(MetadataKey) |> ignore type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = + let unwrapOptionFields = fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption + interface IOpenApiSchemaTransformer with member _.TransformAsync(schema: OpenApiSchema, ctx: OpenApiSchemaTransformerContext, ct: CancellationToken) : Task = let t = ctx.JsonTypeInfo.Type @@ -186,7 +182,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let getFieldPropertySchema (ty: Type) = task { match ty with - | UnionHelpers.FSharpOptionType innerType when fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption -> + | OpenApiSchemaHelpers.OptionOrValueOptionType innerType when unwrapOptionFields -> let! innerSchema = getOrCreateSchema innerType let optionSchema = OpenApiSchema() SchemaCopy.copyTo optionSchema innerSchema diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs index d00a82a..7f05d4f 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs @@ -1,6 +1,7 @@ module SelectView.FSharp.SystemTextJson.OpenApi.Tests.OpenApiOptionTests open System +open System.Text.Json open System.Text.Json.Nodes open System.Text.Json.Serialization open System.Threading.Tasks @@ -10,6 +11,7 @@ open SelectView.FSharp.SystemTextJson.OpenApi open Giraffe open Giraffe.EndpointRouting open Giraffe.OpenApi +open Microsoft.AspNetCore.OpenApi open SelectView.FSharp.SystemTextJson.OpenApi.Tests.OpenApiTestSetup open Xunit @@ -19,6 +21,13 @@ type RecordWithOption = { [] Maybe: string option } type RecordWithVoption = { [] MaybeV: string voption } +[] +type RecordWithUnwrapOverride = { [] MaybeV: string voption } + +type UnionWithVoption = + | WithVoption of maybeV: string voption + | WithNumber of n: int + let private endpoints : Endpoint list = [ POST [ @@ -57,8 +66,36 @@ let private endpoints : Endpoint list = ) ) ] + POST [ + route "/record-with-unwrap-override" (text "ok") + |> addOpenApi( + OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |])) + ) + ] + POST [ + route "/union-with-voption" (text "ok") + |> addOpenApi( + OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |])) + ) + ] ] +let private shippedTransformersFor (fsOptions: JsonFSharpOptions) : IOpenApiSchemaTransformer list = + [ OptionSchemaTransformer(fsOptions) + JsonNodeSchemaTransformer() + CollectionsSchemaTransformer() + RecordSchemaTransformer(fsOptions) + TupleSchemaTransformer() + UnionSchemaTransformer(fsOptions) + EnumSchemaTransformer() ] + +let private shippedTransformers = shippedTransformersFor fsharpJsonOptions + +let private serializeWith (fsOptions: JsonFSharpOptions) value = + JsonSerializer.Serialize(value, fsOptions.ToJsonSerializerOptions()) + +let private serialize value = serializeWith fsharpJsonOptions value + let private getOptionPropertySchema (document: JsonNode) = getRecordPropertySchema document "/record-with-option" "maybe" @@ -114,7 +151,7 @@ let ``Option schema matches snapshot`` () : Task = let ``option property schema matches snapshot`` () : Task = task { let! builtIn = - fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints [ OptionSchemaTransformer(fsharpJsonOptions) ]) + fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers) let schema = getOptionPropertySchema builtIn @@ -128,14 +165,51 @@ let ``option property schema matches snapshot`` () : Task = let ``voption property schema matches snapshot`` () : Task = task { let! builtIn = - fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints [ OptionSchemaTransformer(fsharpJsonOptions) ]) + fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers) let schema = getVoptionPropertySchema builtIn |> canonicalizeJson |> fun x -> x.ToJsonString(jsonOptions) - %schema.Should().Be(expectedOptionStringSchema) + %serialize({ RecordWithVoption.MaybeV = ValueNone }).Should().Be("""{"maybeV":null}""") + %schema.Should().Be(expectedOptionPropertySchema) + } + +[] +let ``voption union field schema allows null`` () : Task = + task { + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers) + + let caseSchema = + getSchemaForPath builtIn "/union-with-voption" + |> expandSchemaRefs builtIn + |> fun union -> getJsonPath union [ "oneOf" ] :?> JsonArray + |> Seq.find (fun case -> not (isNull (getJsonPath case [ "properties" ]).["maybeV"])) + + let schema = + getJsonPath caseSchema [ "properties"; "maybeV" ] + |> canonicalizeJson + |> fun x -> x.ToJsonString(jsonOptions) + + %serialize(WithVoption ValueNone).Should().Be("""{"kind":"WithVoption","maybeV":null}""") + %schema.Should().Be(expectedOptionPropertySchema) + } + +[] +let ``voption field follows the global UnwrapOption, not the parent record's override`` () : Task = + task { + let fsOptions = fsharpJsonOptions.WithUnwrapOption(false) + + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let schema = + getRecordPropertySchema builtIn "/record-with-unwrap-override" "maybeV" + |> expandSchemaRefs builtIn + |> fun x -> x.ToJsonString() + + %(serializeWith fsOptions { RecordWithUnwrapOverride.MaybeV = ValueNone }).Should().Be("""{"maybeV":{"kind":"ValueNone"}}""") + %schema.Should().Contain("\"ValueNone\"").And.NotContain("\"null\"") } []