diff --git a/README.md b/README.md index a4c5a16..bcb17e5 100644 --- a/README.md +++ b/README.md @@ -8,16 +8,19 @@ 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 record and union - fields +- `option` and `voption`: the inner value, and `null` for record fields, + union fields and tuple elements - records: required and optional properties, including `Skippable<'T>` fields + and `SkippableOptionFields` - unions: tags, internal, adjacent and external encodings, named fields, unwrapped cases, fieldless cases as strings, unions of only fieldless cases as string enums, and one component for each case (except string-enum and unwrapped single-case unions) - tuples, F# collections (`list`, `Set`, `Map`), and `JsonObject` - enums: string and number encodings, also when nullable -- per-type options from `[]` +- per-type options from `WithOverrides` and `[]`, + merged with the global options the same way as FSharp.SystemTextJson + (`WithOverrideMembers` and `MapFormat` are not supported) The package targets .NET 10 and OpenAPI 3.1. diff --git a/skills/fsharp-systemtextjson-openapi/SKILL.md b/skills/fsharp-systemtextjson-openapi/SKILL.md index 619649d..6690955 100644 --- a/skills/fsharp-systemtextjson-openapi/SKILL.md +++ b/skills/fsharp-systemtextjson-openapi/SKILL.md @@ -50,31 +50,38 @@ reads. - Giraffe: register `services.AddSingleton(Json.Serializer(jsonOptions))`, where `jsonOptions` has the same settings and `fsOptions` added. -2. To change one type, put `[]` on that type and - call `WithAllowOverride()` on the global options. The transformers read - this attribute. Do not use `JsonFSharpOptions.WithOverrides`: the - serializer applies it, but the transformers do not, so the schema stays - wrong. -3. The attribute does not inherit the global options. Set every option that - the type needs (for example the union tag name) in the attribute. +2. To change one type, use `JsonFSharpOptions.WithOverrides`, or put + `[]` on the type and call `WithAllowOverride()` + on the global options (without it, the attribute is ignored). The + transformers apply both the same way as FSharp.SystemTextJson. +3. Per-type options inherit only the union encoding, and only when they do not + set it. Every other option (for example the union tag name) takes the + FSharp.SystemTextJson default, not the global value. Set every option that + the type needs. An `option` or `voption` field takes `UnwrapOption` from + the options for `option<_>` or `voption<_>` (global or overridden). + Whether a `None` field is left out follows the `SkippableOptionFields` of + the record or union that contains it. 4. If you add the transformers yourself with `AddOpenApi`, add `fsOptions` to `JsonOptions`, and add the two document transformers `UnionCaseComponentsDocumentTransformer()` and `NullableEnumDocumentTransformer()` last, after your own document transformers. -5. The transformers do not model `WithSkippableOptionFields` or `MapFormat`. - With these options the schema does not match the JSON. +5. The transformers do not model `MapFormat` or `WithOverrideMembers`. With + these options the schema does not match the JSON. ## What the schema shows -- `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. +- `option` or `voption` in a record field, a union field or a tuple element: + 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 - `JsonIgnoreCondition.WhenWritingNull`, every field is optional. - `[]` makes a field required. +- Record and named union fields: a `Skippable<'T>` field is optional. An + `option` or `voption` field is optional with + `SkippableOptionFields.Always`, or with `FromJsonSerializerOptions` (the + default) and `JsonIgnoreCondition.WhenWritingNull`. With `WhenWritingNull`, + other fields are optional too. `[]` makes a record field + required. - Unions: the encoding from the options (internal tag, adjacent tag, external tag, untagged, named fields, unwrapped record cases, unwrapped single-field cases, unwrapped single-case unions). With `UnwrapFieldlessTags`, a diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Bootstrap.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Bootstrap.fs index f83abc7..69333cd 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Bootstrap.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Bootstrap.fs @@ -35,7 +35,7 @@ type DependencyExtension() = JsonNodeSchemaTransformer() CollectionsSchemaTransformer() RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) EnumSchemaTransformer() ] diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs index fcd20d3..b7ecf39 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs @@ -101,18 +101,8 @@ module internal OpenApiSchemaHelpers = Enum = ResizeArray([ enumValue ]) ) - let rec unwrapReferenceSchema (schema: IOpenApiSchema) : IOpenApiSchema = - match schema with - | :? OpenApiSchemaReference as schemaReference -> - match schemaReference.Target with - | NonNull target -> unwrapReferenceSchema target - | Null -> schema - | _ -> schema - - let enumIsEmpty (schema: IOpenApiSchema) = - match schema.Enum with - | null -> true - | enumValues -> enumValues.Count = 0 + let anyOfSchema (schemas: IOpenApiSchema seq) = + OpenApiSchema(AnyOf = ResizeArray(schemas)) let getOrCreateDeterministicSchema (ctx: OpenApiSchemaTransformerContext) @@ -125,3 +115,36 @@ module internal OpenApiSchemaHelpers = SchemaCopy.copyTo normalizedSchema schema return normalizePrimitiveStringCoercion normalizedSchema } + + let getOrCreateFieldSchema + (fsOptions: JsonFSharpOptions) + (ctx: OpenApiSchemaTransformerContext) + (ct: CancellationToken) + (t: Type) + : Task = + task { + match t with + | OptionOrValueOptionType innerType when + (FsOptions.getEffectiveFsOptions t fsOptions).UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption + -> + let! innerSchema = getOrCreateDeterministicSchema ctx ct innerType + let optionSchema = OpenApiSchema() + SchemaCopy.copyTo optionSchema innerSchema + addNull optionSchema innerSchema + return optionSchema + | _ -> return! getOrCreateDeterministicSchema ctx ct t + } + + let isSkippableType (t: Type) = + t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> + + let skippableInner (t: Type) = + if isSkippableType t then t.GetGenericArguments()[0] else t + + let canSkipField (options: System.Text.Json.JsonSerializerOptions) (fsOptions: JsonFSharpOptions) (t: Type) = + match t with + | OptionOrValueOptionType _ -> + fsOptions.SkippableOptionFields = SkippableOptionFields.Always + || (ignoreNullValues options + && fsOptions.SkippableOptionFields = SkippableOptionFields.FromJsonSerializerOptions) + | _ -> ignoreNullValues options || isSkippableType t diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/FsOptions.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/FsOptions.fs index 0b6e455..f2956ba 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/FsOptions.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/FsOptions.fs @@ -5,14 +5,29 @@ open System.Text.Json.Serialization module internal FsOptions = - let private customOptions (t: Type) = - match t.GetCustomAttributes(typedefof, false) with - | [| atr |] -> - match atr with - | :? IJsonFSharpConverterAttribute as converter -> Some converter.Options + let private tryGetTypeOrGeneric (t: Type) (overrides: Collections.Generic.IDictionary | null) = + match overrides with + | Null -> None + | NonNull overrides -> + match overrides.TryGetValue t with + | true, options -> Some options + | _ when t.IsGenericType -> + match overrides.TryGetValue(t.GetGenericTypeDefinition()) with + | true, options -> Some options + | _ -> None | _ -> None - | _ -> None let getEffectiveFsOptions (t: Type) (fsOptions: JsonFSharpOptions) = - customOptions t |> Option.defaultValue fsOptions + let inheritUnionEncoding (options: JsonFSharpOptions) = + if options.UnionEncoding.HasFlag JsonUnionEncoding.Inherit then + options.WithUnionEncoding(fsOptions.UnionEncoding) + else + options + match tryGetTypeOrGeneric t (fsOptions.Overrides fsOptions) with + | Some options -> inheritUnionEncoding options + | None when fsOptions.AllowOverride -> + match t.GetCustomAttributes(typeof, true) with + | [||] -> fsOptions + | attributes -> inheritUnionEncoding (attributes[0] :?> IJsonFSharpConverterAttribute).Options + | None -> fsOptions diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs index 6bbccb1..6d41708 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs @@ -12,15 +12,6 @@ open Microsoft.OpenApi module private RecordHelpers = - let isSkippableType (t: Type) = - t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> - - let (|SkippableType|_|) (t: Type) = - if isSkippableType t then - Some(t.GetGenericArguments()[0]) - else - None - let getRecordProperties (fsOptions: JsonFSharpOptions) (recordType: Type) = let fields = FSharpType.GetRecordFields(recordType, true) @@ -47,8 +38,7 @@ module private RecordHelpers = || (p.GetCustomAttributes(typeof, true) |> Seq.isEmpty |> not)) -type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = - let unwrapOptionFields = fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption +type RecordSchemaTransformer(globalFsOptions: JsonFSharpOptions) = interface IOpenApiSchemaTransformer with member _.TransformAsync @@ -61,11 +51,7 @@ type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = // Preserve schema identity so records stay component schemas (not inlined everywhere). let originalId = schema.Id let originalMetadata = schema.Metadata - let fsOptions = FsOptions.getEffectiveFsOptions t fsOptions - let ignoreNulls = OpenApiSchemaHelpers.ignoreNullValues ctx.JsonTypeInfo.Options - - let getOrCreateSchema ty = - OpenApiSchemaHelpers.getOrCreateDeterministicSchema ctx ct ty + let fsOptions = FsOptions.getEffectiveFsOptions t globalFsOptions let props = Dictionary(StringComparer.Ordinal) let required = HashSet(StringComparer.Ordinal) @@ -91,27 +77,12 @@ type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = |> not not explicitlyRequired - && (ignoreNulls || RecordHelpers.isSkippableType p.PropertyType) - - let effectiveType = - match p.PropertyType with - | RecordHelpers.SkippableType inner -> inner - | _ -> p.PropertyType - - let propertySchemaTask = - match effectiveType with - | OpenApiSchemaHelpers.OptionOrValueOptionType innerType when unwrapOptionFields -> - task { - let! innerSchema = getOrCreateSchema innerType - - let optionSchema = OpenApiSchema() - SchemaCopy.copyTo optionSchema innerSchema - OpenApiSchemaHelpers.addNull optionSchema innerSchema - return optionSchema - } - | _ -> getOrCreateSchema effectiveType - - let! propertySchema = propertySchemaTask + && OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options fsOptions p.PropertyType + + let effectiveType = OpenApiSchemaHelpers.skippableInner p.PropertyType + + let! propertySchema = + OpenApiSchemaHelpers.getOrCreateFieldSchema globalFsOptions ctx ct effectiveType props[name] <- propertySchema 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 3c897e8..34bc295 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj @@ -17,8 +17,8 @@ - + diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs index 3a7808b..18d70cb 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs @@ -2,13 +2,14 @@ namespace SelectView.FSharp.SystemTextJson.OpenApi open System open System.Collections.Generic +open System.Text.Json.Serialization open Microsoft.FSharp.Reflection open System.Threading open System.Threading.Tasks open Microsoft.AspNetCore.OpenApi open Microsoft.OpenApi -type TupleSchemaTransformer() = +type TupleSchemaTransformer(fsOptions: JsonFSharpOptions) = interface IOpenApiSchemaTransformer with member _.TransformAsync(schema: OpenApiSchema, ctx: OpenApiSchemaTransformerContext, ct: CancellationToken) : Task = task { @@ -20,28 +21,14 @@ type TupleSchemaTransformer() = let! elementSchemas = distinctElementTypes - |> Array.map (OpenApiSchemaHelpers.getOrCreateDeterministicSchema ctx ct) + |> Array.map (OpenApiSchemaHelpers.getOrCreateFieldSchema fsOptions ctx ct) |> Task.WhenAll let elementSchemaRefs = elementSchemas |> Array.map (fun schema -> schema :> IOpenApiSchema) - let hasPlainString = - elementSchemaRefs - |> Seq.map OpenApiSchemaHelpers.unwrapReferenceSchema - |> Seq.exists (fun s -> s.Type = Nullable(JsonSchemaType.String) && OpenApiSchemaHelpers.enumIsEmpty s) - - let hasEnumString = - elementSchemaRefs - |> Seq.map OpenApiSchemaHelpers.unwrapReferenceSchema - |> Seq.exists (fun s -> s.Type = Nullable(JsonSchemaType.String) && not (OpenApiSchemaHelpers.enumIsEmpty s)) - - let itemUnionSchema = - if hasPlainString && hasEnumString then - OpenApiSchema(AnyOf = ResizeArray(elementSchemaRefs)) - else - OpenApiSchema(OneOf = ResizeArray(elementSchemaRefs)) + let itemUnionSchema = OpenApiSchemaHelpers.anyOfSchema elementSchemaRefs let tupleSchema = OpenApiSchema( diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs index fc48143..c8b1e3f 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs @@ -22,9 +22,6 @@ module private UnionHelpers = let isFSharpListType (t: Type) = t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> - let isSkippableType (t: Type) = - t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> - let getJsonFieldNames (getAttributes: Type -> obj[]) = getAttributes typeof |> Seq.choose (function @@ -153,13 +150,12 @@ module private UnionCasePromotionPlan = | Null -> () | NonNull metadata -> metadata.Remove(MetadataKey) |> ignore -type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = - let unwrapOptionFields = fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption +type UnionSchemaTransformer(globalFsOptions: JsonFSharpOptions) = interface IOpenApiSchemaTransformer with member _.TransformAsync(schema: OpenApiSchema, ctx: OpenApiSchemaTransformerContext, ct: CancellationToken) : Task = let t = ctx.JsonTypeInfo.Type - let fsOptions = FsOptions.getEffectiveFsOptions t fsOptions + let fsOptions = FsOptions.getEffectiveFsOptions t globalFsOptions if not (FSharpType.IsUnion(t)) @@ -174,22 +170,11 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let originalMetadata = schema.Metadata let cases = FSharpType.GetUnionCases t - let ignoreNullValues = OpenApiSchemaHelpers.ignoreNullValues ctx.JsonTypeInfo.Options - let getOrCreateSchema (ty: Type) = OpenApiSchemaHelpers.getOrCreateDeterministicSchema ctx ct ty let getFieldPropertySchema (ty: Type) = - task { - match ty with - | OpenApiSchemaHelpers.OptionOrValueOptionType innerType when unwrapOptionFields -> - let! innerSchema = getOrCreateSchema innerType - let optionSchema = OpenApiSchema() - SchemaCopy.copyTo optionSchema innerSchema - OpenApiSchemaHelpers.addNull optionSchema innerSchema - return optionSchema - | _ -> return! getOrCreateSchema ty - } + OpenApiSchemaHelpers.getOrCreateFieldSchema globalFsOptions ctx ct ty let createUnionFieldsObjectSchema (uci: UnionCaseInfo) = task { @@ -203,7 +188,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let! fieldSchema = getFieldPropertySchema fieldInfo.PropertyType props[name] <- fieldSchema - if not ignoreNullValues && not (UnionHelpers.isSkippableType fieldInfo.PropertyType) then + if not (OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options fsOptions fieldInfo.PropertyType) then required.Add(name) |> ignore return @@ -248,24 +233,19 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = && FSharpType.IsRecord fields[0].PropertyType then let recordType = fields[0].PropertyType + let recordFsOptions = FsOptions.getEffectiveFsOptions recordType fsOptions let recordProps = - UnionHelpers.getRecordProperties fsOptions recordType + UnionHelpers.getRecordProperties recordFsOptions recordType |> Array.filter (fun p -> p.GetCustomAttributes(typeof, true) |> Array.isEmpty) for p in recordProps do let name = UnionHelpers.getPropertyName ctx.JsonTypeInfo.Options p let canBeSkipped = - ignoreNullValues || UnionHelpers.isSkippableType p.PropertyType + OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options recordFsOptions p.PropertyType - let effectiveType = - if UnionHelpers.isSkippableType p.PropertyType then - p.PropertyType.GetGenericArguments()[0] - else - p.PropertyType - - let! fieldSchema = getFieldPropertySchema effectiveType + let! fieldSchema = getFieldPropertySchema (OpenApiSchemaHelpers.skippableInner p.PropertyType) props[name] <- fieldSchema @@ -279,7 +259,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let! fieldSchema = getFieldPropertySchema fieldInfo.PropertyType props[name] <- fieldSchema - if not ignoreNullValues && not (UnionHelpers.isSkippableType fieldInfo.PropertyType) then + if not (OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options fsOptions fieldInfo.PropertyType) then required.Add(name) |> ignore return @@ -330,7 +310,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = || (fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapRecordCases && FSharpType.IsRecord fields[0].PropertyType)) then - getOrCreateSchema fields[0].PropertyType + getFieldPropertySchema fields[0].PropertyType elif fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.NamedFields then createUnionFieldsObjectSchema uci else @@ -350,7 +330,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = else let! payloadSchema = if fields.Length = 1 && fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapSingleFieldCases then - getOrCreateSchema fields[0].PropertyType + getFieldPropertySchema fields[0].PropertyType elif fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.NamedFields then createUnionFieldsObjectSchema uci elif fields.Length = 0 then @@ -397,7 +377,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let! fieldSchemas = distinctFieldTypes - |> Array.map getOrCreateSchema + |> Array.map getFieldPropertySchema |> Task.WhenAll let tagSchema = @@ -406,21 +386,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let elementSchemas = Array.append [| tagSchema |] (fieldSchemas |> Array.map (fun x -> x :> IOpenApiSchema)) - let hasPlainString = - elementSchemas - |> Seq.map OpenApiSchemaHelpers.unwrapReferenceSchema - |> Seq.exists (fun s -> s.Type = Nullable(JsonSchemaType.String) && OpenApiSchemaHelpers.enumIsEmpty s) - - let hasEnumString = - elementSchemas - |> Seq.map OpenApiSchemaHelpers.unwrapReferenceSchema - |> Seq.exists (fun s -> s.Type = Nullable(JsonSchemaType.String) && not (OpenApiSchemaHelpers.enumIsEmpty s)) - - let itemUnionSchema = - if hasPlainString && hasEnumString then - OpenApiSchema(AnyOf = ResizeArray(elementSchemas)) - else - OpenApiSchema(OneOf = ResizeArray(elementSchemas)) + let itemUnionSchema = OpenApiSchemaHelpers.anyOfSchema elementSchemas let tupleSchema = OpenApiSchema( diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs index 0816cb5..59b993d 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs @@ -92,7 +92,7 @@ let ``Collections use array and dictionary schemas matching their JSON encoding` OptionSchemaTransformer(fsOptions) CollectionsSchemaTransformer() RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) ]) @@ -122,7 +122,7 @@ let ``Collections use array and dictionary schemas matching their JSON encoding` %((entryTuple["maxItems"] :?> JsonValue).GetValue()).Should().Be(2) let entryItemTypes = - entryTuple["items"]["oneOf"] :?> JsonArray + entryTuple["items"]["anyOf"] :?> JsonArray |> Seq.collect getSchemaTypes |> Set.ofSeq diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs index 7f05d4f..b38d9fe 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs @@ -28,6 +28,31 @@ type UnionWithVoption = | WithVoption of maybeV: string voption | WithNumber of n: int +type RecordWithOptionTuple = { [] Pair: string option * int } + +type RecordWithTwoOptions = { [] Pair: string option * int option } + +type PositionalOptionUnion = + | PosPair of string option * int + | PosEmpty + +type SingleOptionFieldUnion = + | OnlyOption of string option + | OnlyNumber of int + +type RecordWithNote = + { [] Name: string + [] Note: string option } + +[] +type RecordSkippingNone = + { [] Name: string + [] Note: string option } + +type UnwrappedRecordCase = + | Wrapped of RecordSkippingNone + | Bare of n: int + let private endpoints : Endpoint list = [ POST [ @@ -78,22 +103,38 @@ let private endpoints : Endpoint list = OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |])) ) ] + POST [ + route "/record-with-option-tuple" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/record-with-two-options" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/positional-option-union" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/single-option-field-union" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/record-with-note" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/record-skipping-none" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/unwrapped-record-case" (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) = @@ -386,3 +427,141 @@ let ``voption property schema matches encoding (WithUnwrapOption disable %valueSomeFieldType.Should().Be("string") } + +let private positionalCases = + [ "internal tag", JsonFSharpOptions.Default().WithUnionInternalTag(), """["PosPair",null,2]""" + "adjacent tag", JsonFSharpOptions.Default(), """{"Case":"PosPair","Fields":[null,2]}""" + "external tag", JsonFSharpOptions.Default().WithUnionExternalTag(), """{"PosPair":[null,2]}""" ] + +[] +let ``option in a tuple element allows null`` () : Task = + task { + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers) + + let schema = + getRecordPropertySchema builtIn "/record-with-option-tuple" "pair" |> expandSchemaRefs builtIn + + let alternatives = itemAlternatives schema + + %serialize({ RecordWithOptionTuple.Pair = (None, 1) }).Should().Be("""{"pair":[null,1]}""") + %(alternatives |> List.map schemaTypes |> Set.ofList).Should().Be(Set.ofList [ Set.ofList [ "string"; "null" ]; Set.singleton "integer" ]) + } + +[] +let ``option in a positional union field allows null`` () : Task = + task { + for (name, fsOptions, expectedJson) in positionalCases do + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let schema = + getSchemaForPath builtIn "/positional-option-union" |> expandSchemaRefs builtIn + + let alternatives = arraySchemasUnder schema |> List.collect itemAlternatives |> List.map schemaTypes + + %(serializeWith fsOptions (PosPair(None, 2))).Should().Be(expectedJson, name) + %(alternatives |> List.contains (Set.ofList [ "string"; "null" ])).Should().BeTrue(name) + %(alternatives |> List.contains (Set.singleton "integer")).Should().BeTrue(name) + } + +[] +let ``option in an unwrapped single-field case allows null`` () : Task = + task { + let fsOptions = JsonFSharpOptions.Default().WithUnionUnwrapSingleFieldCases() + + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let schema = + getSchemaForPath builtIn "/single-option-field-union" |> expandSchemaRefs builtIn + + let fieldsTypes = + getJsonPath schema [ "oneOf" ] :?> JsonArray + |> Seq.map nonNull + |> Seq.find (fun case -> (getJsonPath case [ "properties"; "Case"; "enum" ]).[0].GetValue() = "OnlyOption") + |> fun case -> getJsonPath case [ "properties"; "Fields" ] |> schemaTypes + + %(serializeWith fsOptions (OnlyOption None)).Should().Be("""{"Case":"OnlyOption","Fields":null}""") + %fieldsTypes.Should().Be(Set.ofList [ "string"; "null" ]) + } + +[] +let ``SkippableOptionFields decides whether an option field is required`` () : Task = + task { + let cases = + [ "global Always", fsharpJsonOptions.WithSkippableOptionFields(SkippableOptionFields.Always), "/record-with-note", + serializeWith (fsharpJsonOptions.WithSkippableOptionFields(SkippableOptionFields.Always)) { RecordWithNote.Name = "x"; Note = None }, + """{"name":"x"}""", Set.ofList [ "name" ] + "attribute Always", fsharpJsonOptions, "/record-skipping-none", + serializeWith fsharpJsonOptions { RecordSkippingNone.Name = "x"; Note = None }, + """{"name":"x"}""", Set.ofList [ "name" ] + "default", fsharpJsonOptions, "/record-with-note", + serializeWith fsharpJsonOptions { RecordWithNote.Name = "x"; Note = None }, + """{"name":"x","note":null}""", Set.ofList [ "name"; "note" ] ] + + for (name, fsOptions, path, json, expectedJson, expectedRequired) in cases do + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let record = getSchemaForPath builtIn path |> dereferenceSchema builtIn + + %json.Should().Be(expectedJson, name) + %(requiredNames record).Should().Be(expectedRequired, name) + } + +[] +let ``a string field equal to the case tag still matches the positional case schema`` () : Task = + task { + let fsOptions = JsonFSharpOptions.Default().WithUnionInternalTag() + + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let caseArrays = getSchemaForPath builtIn "/positional-option-union" |> expandSchemaRefs builtIn |> arraySchemasUnder + + %(serializeWith fsOptions (PosPair(Some "PosPair", 2))).Should().Be("""["PosPair","PosPair",2]""") + %(caseArrays |> List.forall (fun a -> isNull ((nonNull a.["items"]).["oneOf"]))).Should().BeTrue() + %(caseArrays |> List.exists (fun a -> itemAlternatives a |> List.map schemaTypes |> List.contains (Set.ofList [ "string"; "null" ]))).Should().BeTrue() + } + +[] +let ``an option override applies to tuple elements`` () : Task = + task { + let fsOptions = + fsharpJsonOptions.WithOverrides(dict [ typedefof>, JsonFSharpOptions.Default().WithUnwrapOption(false) ]) + + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let schema = + getRecordPropertySchema builtIn "/record-with-option-tuple" "pair" |> expandSchemaRefs builtIn + + let alternatives = itemAlternatives schema |> List.map schemaTypes + + %(serializeWith fsOptions { RecordWithOptionTuple.Pair = (Some "a", 1) }).Should().Be("""{"pair":[{"Case":"Some","Fields":["a"]},1]}""") + %(alternatives |> Set.ofList).Should().Be(Set.ofList [ Set.ofList [ "object"; "null" ]; Set.singleton "integer" ]) + } + +[] +let ``an unwrapped record case uses the record's own SkippableOptionFields`` () : Task = + task { + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers) + + let caseSchema = + getSchemaForPath builtIn "/unwrapped-record-case" + |> expandSchemaRefs builtIn + |> fun union -> getJsonPath union [ "oneOf" ] :?> JsonArray + |> Seq.map nonNull + |> Seq.find (fun case -> not (isNull (getJsonPath case [ "properties" ]).["name"])) + + %serialize(Wrapped { RecordSkippingNone.Name = "x"; Note = None }).Should().Be("""{"kind":"Wrapped","name":"x"}""") + %(requiredNames caseSchema).Should().Be(Set.ofList [ "kind"; "name" ]) + } + +[] +let ``a null that matches two option elements uses anyOf`` () : Task = + task { + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers) + + let schema = + getRecordPropertySchema builtIn "/record-with-two-options" "pair" |> expandSchemaRefs builtIn + + %serialize({ RecordWithTwoOptions.Pair = (None, None) }).Should().Be("""{"pair":[null,null]}""") + %(itemAlternatives schema |> List.map schemaTypes |> Set.ofList).Should().Be(Set.ofList [ Set.ofList [ "string"; "null" ]; Set.ofList [ "integer"; "null" ] ]) + } + diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiPerTypeOptionsTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiPerTypeOptionsTests.fs index 78cb9c9..147ed9d 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiPerTypeOptionsTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiPerTypeOptionsTests.fs @@ -29,6 +29,15 @@ type ExternalTagUnionPerType = | Fieldless | Pair of string * int +[] +type InheritingShape = + | Circle of radius: float + | Dot + +type OverriddenShape = + | Square of side: float + | NoShape + let private endpoints : Endpoint list = [ POST [ @@ -49,6 +58,14 @@ let private endpoints : Endpoint list = ) ) ] + POST [ + route "/inheriting-shape" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/overridden-shape" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] ] let private getSchemaTypes (schema: JsonNode) = @@ -88,7 +105,7 @@ let ``Per-type JsonFSharpConverterAttribute options shape record and union schem OptionSchemaTransformer(fsOptions) CollectionsSchemaTransformer() RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) ]) @@ -109,3 +126,30 @@ let ``Per-type JsonFSharpConverterAttribute options shape record and union schem %(unionProperties.Contains("Fieldless")).Should().BeTrue() %(unionProperties.Contains("Pair")).Should().BeTrue() } + +let private shapeCases = + let withOverride = + fsharpJsonOptions.WithOverrides( + dict [ typeof, JsonFSharpOptions.InheritUnionEncoding().WithUnionTagName("shape") ] + ) + + [ "attribute inherits the union encoding", fsharpJsonOptions, "/inheriting-shape", + serializeWith fsharpJsonOptions (Circle 1.0), """{"type":"Circle","radius":1}""", "type", "kind" + "WithOverrides applies", withOverride, "/overridden-shape", + serializeWith withOverride (Square 1.0), """{"shape":"Square","side":1}""", "shape", "kind" + "attribute ignored without AllowOverride", fsharpJsonOptions.WithAllowOverride(false), "/inheriting-shape", + serializeWith (fsharpJsonOptions.WithAllowOverride(false)) (Circle 1.0), """{"kind":"Circle","radius":1}""", "kind", "type" ] + +[] +let ``Per-type options merge with the global options like FSharp.SystemTextJson`` () : Task = task { + for (name, fsOptions, path, json, expectedJson, tag, absentTag) in shapeCases do + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let names = getSchemaForPath builtIn path |> expandSchemaRefs builtIn |> collectPropertyNames |> Set.ofSeq + + %json.Should().Be(expectedJson, name) + %(names.Contains tag).Should().BeTrue(name) + %(names.Contains absentTag).Should().BeFalse(name) + %(names.Contains "Fields").Should().BeFalse(name) +} + diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiRecordTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiRecordTests.fs index 4fca3e8..eb123b6 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiRecordTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiRecordTests.fs @@ -95,7 +95,7 @@ let ``Record schema exposes fields, JSON names, and required properties`` () : T OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) ]) let schema = getSchemaForPath builtIn "/record-sample" |> expandSchemaRefs builtIn @@ -125,7 +125,7 @@ let ``Record schema is referenced (not inlined)`` () : Task = task { OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) ]) getSchemaForPath builtIn "/record-sample" |> assertSchemaIsRef @@ -143,7 +143,7 @@ let ``JsonObject record field allows arbitrary object properties`` () : Task = t JsonNodeSchemaTransformer() CollectionsSchemaTransformer() RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) ]) let schema = diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs index 99f94a3..9fe305d 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs @@ -227,3 +227,43 @@ let createBuiltInOpenApiApp return app } + +let shippedTransformersFor (fsOptions: JsonFSharpOptions) : IOpenApiSchemaTransformer list = + [ OptionSchemaTransformer(fsOptions) + JsonNodeSchemaTransformer() + CollectionsSchemaTransformer() + RecordSchemaTransformer(fsOptions) + TupleSchemaTransformer(fsOptions) + UnionSchemaTransformer(fsOptions) + EnumSchemaTransformer() ] + +let serializeWith (fsOptions: JsonFSharpOptions) (value: 'T) = + JsonSerializer.Serialize<'T>(value, fsOptions.ToJsonSerializerOptions()) + +let itemAlternatives (arraySchema: JsonNode) = + match arraySchema["items"] with + | :? JsonObject as items -> + match items["anyOf"] with + | :? JsonArray as alternatives -> alternatives |> Seq.map nonNull |> List.ofSeq + | _ -> [ items ] + | _ -> failwith $"Expected items in {arraySchema.ToJsonString()}" + +let schemaTypes (schema: JsonNode) = + match schema["type"] with + | :? JsonValue as v -> Set.singleton (v.GetValue()) + | :? JsonArray as types -> types |> Seq.map (fun v -> (nonNull v).GetValue()) |> Set.ofSeq + | _ -> Set.empty + +let rec arraySchemasUnder (node: JsonNode) : JsonNode list = + match node with + | :? JsonObject as obj -> + let self = if schemaTypes node = Set.singleton "array" && not (isNull obj["items"]) then [ node ] else [] + self @ (obj |> Seq.toList |> List.collect (fun kvp -> match kvp.Value with | Null -> [] | NonNull v -> arraySchemasUnder v)) + | :? JsonArray as values -> values |> Seq.toList |> List.collect (fun v -> match v with | Null -> [] | NonNull v -> arraySchemasUnder v) + | _ -> [] + +let requiredNames (schema: JsonNode) = + match schema["required"] with + | :? JsonArray as names -> names |> Seq.map (fun n -> (nonNull n).GetValue()) |> Set.ofSeq + | _ -> Set.empty + diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs index 6b2987c..20507ce 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs @@ -52,7 +52,7 @@ let ``Tuple schema is a fixed-length array of its element types`` () : Task = ta OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) ]) let schema = getSchemaForPath builtIn "/tuple-sample" |> expandSchemaRefs builtIn @@ -61,7 +61,7 @@ let ``Tuple schema is a fixed-length array of its element types`` () : Task = ta %((schema["minItems"] :?> JsonValue).GetValue()).Should().Be(2) %((schema["maxItems"] :?> JsonValue).GetValue()).Should().Be(2) - let itemAlternatives = schema["items"]["oneOf"] :?> JsonArray + let itemAlternatives = schema["items"]["anyOf"] :?> JsonArray let itemTypes = itemAlternatives |> Seq.collect getSchemaTypes |> Set.ofSeq @@ -81,7 +81,7 @@ let ``Tuple schema is inlined`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) getSchemaForPath builtIn "/tuple-sample" |> assertSchemaIsInline diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionEncodingTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionEncodingTests.fs index bc35481..f4d8cfa 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionEncodingTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionEncodingTests.fs @@ -39,7 +39,7 @@ let private createTransformers fsOptions = [ OptionSchemaTransformer(fsOptions) :> IOpenApiSchemaTransformer CollectionsSchemaTransformer() :> IOpenApiSchemaTransformer RecordSchemaTransformer(fsOptions) :> IOpenApiSchemaTransformer - TupleSchemaTransformer() :> IOpenApiSchemaTransformer + TupleSchemaTransformer(fsOptions) :> IOpenApiSchemaTransformer UnionSchemaTransformer(fsOptions) :> IOpenApiSchemaTransformer ] let rec private collectPropertyNames (node: JsonNode) = seq { diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionTests.fs index 6e66467..1e5097c 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionTests.fs @@ -443,7 +443,7 @@ let ``Multi-case union schema is referenced (not inlined)`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) getSchemaForPath builtIn "/union-sample" |> assertSchemaIsRef @@ -463,7 +463,7 @@ let ``Multi-case union branches are referenced (not inlined)`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) let unionSchema = @@ -496,7 +496,7 @@ let ``Single-case fieldless union schema is inlined as case object`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) let schema = getResponseSchemaForPath builtIn "/union-single-case-fieldless" 200 @@ -531,7 +531,7 @@ let ``Single-case single-field union schema is unwrapped`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) let schema = getResponseSchemaForPath builtIn "/union-single-case-single-field" 200 @@ -755,7 +755,7 @@ let ``Generic non-Result unions with nested payloads get stable wrapper and case [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) let wrapperRefResultArray = getResponseSchemaRef builtIn "/union-envelope-result-array" @@ -855,7 +855,7 @@ let ``Optional payload-union property is a single nullable union component`` () [ OptionSchemaTransformer(fsharpJsonOptions) UnionSchemaTransformer(fsharpJsonOptions) RecordSchemaTransformer(fsharpJsonOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsharpJsonOptions) ] ) let unionId = @@ -916,7 +916,7 @@ let ``Optional fieldless-tag union property lists null in its enum`` () : Task = [ OptionSchemaTransformer(fsharpJsonOptions) UnionSchemaTransformer(fsharpJsonOptions) RecordSchemaTransformer(fsharpJsonOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsharpJsonOptions) ] ) let statusSchema =