Created
July 7, 2020 16:32
-
-
Save moxley/ed8efe939bc1d2be89a55432551faedc to your computer and use it in GitHub Desktop.
Generate a Typescript interface from an OpenApiSpex Schema struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MoxleyApiUtil.TypescriptInterfaceGenerator do | |
alias OpenApiSpex.Schema | |
def to_ts_interface(%Schema{type: :object} = schema) do | |
header = "interface #{schema.title} {" | |
body = Enum.map(schema.properties, &to_ts_property_line/1) |> Enum.join("\n") | |
header <> "\n" <> body <> "\n}\n" | |
end | |
defp to_ts_property_line({name, schema}) do | |
ts_type = to_ts_type(schema) | |
" #{name}: #{ts_type};" | |
end | |
defp to_ts_type(module) when is_atom(module) do | |
to_ts_type(module.schema()) | |
end | |
defp to_ts_type(%{type: :object} = schema) do | |
to_ts_interface(schema) | |
end | |
defp to_ts_type(%{type: :string, format: :datetime}) do | |
"Date" | |
end | |
defp to_ts_type(%{type: :string, enum: [_ | _] = enum}) do | |
enum |> Enum.map(&Jason.encode!/1) |> Enum.join(" | ") | |
end | |
defp to_ts_type(%{type: type}) do | |
type | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment