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
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `[<JsonFSharpConverter(...)>]`
- per-type options from `WithOverrides` and `[<JsonFSharpConverter(...)>]`,
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.

Expand Down
37 changes: 22 additions & 15 deletions skills/fsharp-systemtextjson-openapi/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,31 +50,38 @@ reads.
- Giraffe: register
`services.AddSingleton<Json.ISerializer>(Json.Serializer(jsonOptions))`,
where `jsonOptions` has the same settings and `fsOptions` added.
2. To change one type, put `[<JsonFSharpConverter(...)>]` 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
`[<JsonFSharpConverter(...)>]` 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.
`[<JsonRequired>]` 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. `[<JsonRequired>]` 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
Expand Down
2 changes: 1 addition & 1 deletion src/SelectView.FSharp.SystemTextJson.OpenApi/Bootstrap.fs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type DependencyExtension() =
JsonNodeSchemaTransformer()
CollectionsSchemaTransformer()
RecordSchemaTransformer(fsOptions)
TupleSchemaTransformer()
TupleSchemaTransformer(fsOptions)
UnionSchemaTransformer(fsOptions)
EnumSchemaTransformer()
]
Expand Down
47 changes: 35 additions & 12 deletions src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs
Original file line number Diff line number Diff line change
Expand Up @@ -101,18 +101,8 @@ module internal OpenApiSchemaHelpers =
Enum = ResizeArray<JsonNode>([ 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<IOpenApiSchema>(schemas))

let getOrCreateDeterministicSchema
(ctx: OpenApiSchemaTransformerContext)
Expand All @@ -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<OpenApiSchema> =
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<Skippable<_>>

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
29 changes: 22 additions & 7 deletions src/SelectView.FSharp.SystemTextJson.OpenApi/FsOptions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,29 @@ open System.Text.Json.Serialization

module internal FsOptions =

let private customOptions (t: Type) =
match t.GetCustomAttributes(typedefof<JsonFSharpConverterAttribute>, false) with
| [| atr |] ->
match atr with
| :? IJsonFSharpConverterAttribute as converter -> Some converter.Options
let private tryGetTypeOrGeneric (t: Type) (overrides: Collections.Generic.IDictionary<Type, JsonFSharpOptions> | 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<IJsonFSharpConverterAttribute>, true) with
| [||] -> fsOptions
| attributes -> inheritUnionEncoding (attributes[0] :?> IJsonFSharpConverterAttribute).Options
| None -> fsOptions
45 changes: 8 additions & 37 deletions src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,6 @@ open Microsoft.OpenApi

module private RecordHelpers =

let isSkippableType (t: Type) =
t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<Skippable<_>>

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)

Expand All @@ -47,8 +38,7 @@ module private RecordHelpers =
|| (p.GetCustomAttributes(typeof<JsonIncludeAttribute>, true) |> Seq.isEmpty |> not))


type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) =
let unwrapOptionFields = fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption
type RecordSchemaTransformer(globalFsOptions: JsonFSharpOptions) =

interface IOpenApiSchemaTransformer with
member _.TransformAsync
Expand All @@ -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<string, IOpenApiSchema>(StringComparer.Ordinal)
let required = HashSet<string>(StringComparer.Ordinal)
Expand All @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
</PropertyGroup>
<ItemGroup>
<Compile Include="SchemaCopy.fs" />
<Compile Include="CommonHelpers.fs" />
<Compile Include="FsOptions.fs" />
<Compile Include="CommonHelpers.fs" />
<Compile Include="Option.fs" />
<Compile Include="JsonNodes.fs" />
<Compile Include="Collections.fs" />
Expand Down
21 changes: 4 additions & 17 deletions src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<IOpenApiSchema>(elementSchemaRefs))
else
OpenApiSchema(OneOf = ResizeArray<IOpenApiSchema>(elementSchemaRefs))
let itemUnionSchema = OpenApiSchemaHelpers.anyOfSchema elementSchemaRefs

let tupleSchema =
OpenApiSchema(
Expand Down
Loading
Loading