Skip to content

Instantly share code, notes, and snippets.

@reitzig
Last active October 12, 2017 21:25
Show Gist options
  • Save reitzig/e6083a0799000cf05f34e286e5904c22 to your computer and use it in GitHub Desktop.
Save reitzig/e6083a0799000cf05f34e286e5904c22 to your computer and use it in GitHub Desktop.
module Domain.SomeTitle exposing (..)
--
import Json.Decode as Decode
exposing
( succeed
, fail
, map
, maybe
, field
, at
, andThen
, oneOf
, nullable
, Decoder
)
import Json.Decode.Pipeline
exposing
( decode
, required
, optional
, custom
)
import Json.Encode as Encode
exposing
( Value
, object
)
type alias SomeTitle =
{ first : String
, second : String
, third : Maybe Third
}
type alias Third =
{ a : String
}
SomeTitleDecoder : Decoder SomeTitle
SomeTitleDecoder =
decode SomeTitle
|> required "first" Decode.string
|> required "second" Decode.string
|> optional "third" (nullable thirdDecoder) Nothing
thirdDecoder : Decoder Third
thirdDecoder =
decode Third
|> required "a" Decode.string
encodeSomeTitle : SomeTitle -> Value
encodeSomeTitle SomeTitle =
let
first =
[ ( "first", Encode.string SomeTitle.first ) ]
second =
[ ( "second", Encode.string SomeTitle.second ) ]
third =
case SomeTitle.third of
Just third ->
[ ( "third", encodeThird third ) ]
Nothing ->
[]
in
object <|
first ++ second ++ third
encodeThird : Third -> Value
encodeThird third =
let
a =
[ ( "a", Encode.string third.a ) ]
in
object <|
a
{
"$schema": "http://json-schema.org/draft-04/schema",
"id": "https://github.com/reitzig/example",
"title": "Some title",
"type": "object",
"required": ["first", "second"],
"additionalProperties": false,
"properties": {
"first": {
"title": "First property",
"type": "string",
"pattern": "[0-9]{4}-[0-9]{2}-[0-9]{2}"
},
"second": {
"title": "The license of this version of the rules",
"type": "string"
},
"third": {
"title": "The language of the contained texts",
"type": "object",
"required": ["a"],
"properties": {
"a": {
"type": "string",
"pattern": "[a-z]{2}(_[a-z]{2})?"
}
}
}
},
"patternProperties": {
"^[0-9]+(\\.[0-9]+)*$": {
"title": "An item",
"type": "object",
"anyOf": [
{ "required": ["title"] },
{ "required": ["text"] }
],
"additionalProperties": false,
"properties": {
"title": {
"type": "string"
},
"text": {
"type": "string"
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment