Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions skills/fsharp-systemtextjson-openapi/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ open Microsoft.OpenApi

module internal OpenApiSchemaHelpers =

let (|OptionOrValueOptionType|_|) (t: Type) =
if
t.IsGenericType
&& (t.GetGenericTypeDefinition() = typedefof<option<_>>
|| t.GetGenericTypeDefinition() = typedefof<voption<_>>)
then
Some(t.GetGenericArguments()[0])
else
None

let private hasSchemaTypeFlag (schemaType: JsonSchemaType) (flag: JsonSchemaType) =
((int schemaType) &&& (int flag)) = int flag

Expand Down
15 changes: 3 additions & 12 deletions src/SelectView.FSharp.SystemTextJson.OpenApi/Option.fs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
| _ ->
Expand Down
12 changes: 3 additions & 9 deletions src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,6 @@ module private RecordHelpers =
else
None

let (|FSharpOptionType|_|) (t: Type) =
if t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<option<_>> then
Some(t.GetGenericArguments()[0])
else
None

let getRecordProperties (fsOptions: JsonFSharpOptions) (recordType: Type) =
let fields = FSharpType.GetRecordFields(recordType, true)

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<PackageId>SelectView.FSharp.SystemTextJson.OpenApi</PackageId>
<Version>0.1.0</Version>
<Version>0.1.1</Version>
<Authors>SelectView</Authors>
<Copyright>Copyright (c) SelectView</Copyright>
<Description>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.</Description>
Expand Down
10 changes: 3 additions & 7 deletions src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,6 @@ open Microsoft.OpenApi

module private UnionHelpers =

let (|FSharpOptionType|_|) (t: Type) =
if t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<option<_>> then
Some(t.GetGenericArguments()[0])
else
None

let isFSharpOptionType (t: Type) =
t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<option<_>>

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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

Expand All @@ -19,6 +21,13 @@ type RecordWithOption = { [<JsonPropertyName "maybe">] Maybe: string option }

type RecordWithVoption = { [<JsonPropertyName "maybeV">] MaybeV: string voption }

[<JsonFSharpConverter(UnwrapOption = true)>]
type RecordWithUnwrapOverride = { [<JsonPropertyName "maybeV">] MaybeV: string voption }

type UnionWithVoption =
| WithVoption of maybeV: string voption
| WithNumber of n: int

let private endpoints : Endpoint list =
[
POST [
Expand Down Expand Up @@ -57,8 +66,36 @@ let private endpoints : Endpoint list =
)
)
]
POST [
route "/record-with-unwrap-override" (text "ok")
|> addOpenApi(
OpenApiConfig(requestBody = RequestBody(typeof<RecordWithUnwrapOverride>, contentTypes = [| "application/json" |]))
)
]
POST [
route "/union-with-voption" (text "ok")
|> addOpenApi(
OpenApiConfig(requestBody = RequestBody(typeof<UnionWithVoption>, 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"

Expand Down Expand Up @@ -114,7 +151,7 @@ let ``Option<string> schema matches snapshot`` () : Task =
let ``option<string> property schema matches snapshot`` () : Task =
task {
let! builtIn =
fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints [ OptionSchemaTransformer(fsharpJsonOptions) ])
fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers)

let schema =
getOptionPropertySchema builtIn
Expand All @@ -128,14 +165,51 @@ let ``option<string> property schema matches snapshot`` () : Task =
let ``voption<string> 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)
}

[<Fact>]
let ``voption<string> 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)
}

[<Fact>]
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\"")
}

[<Fact>]
Expand Down
Loading