Provides functions to encode resources to a Json.Encode.Value. You can then finally
encode it to a json api string with Json.Encode.encode.
Encodes a list of resources.
type alias Post =
{ id : String
, links : Dict String String
, title : String
, content : String
, creator : Creator
, comments : List Comment
}
type alias Creator =
{ id : String
, links : Dict String String
, firstname : String
, lastname : String
}
type alias Comment =
{ id : String
, links : Dict String String
, content : String
, email : String
}
posts : List Post
posts =
[ postNoLink, post2 ]
postNoLink : Post
postNoLink =
{ id = "post-1"
, links = Dict.empty
, title = "Post no link"
, content = "Post content no link"
, creator = creator
, comments = [ comment1, comment2 ]
}
post2 : Post
post2 =
{ id = "post-2"
, links = Dict.fromList [ ( "self", "http://url-to-post/2" ) ]
, title = "Post 2"
, content = "Post content 2"
, creator = creator
, comments = [ comment3 ]
}
creator : Creator
creator =
{ id = "creator-1"
, links = Dict.fromList [ ( "self", "http://url-to-creator/1" ) ]
, firstname = "John"
, lastname = "Doe"
}
comment1 : Comment
comment1 =
{ id = "comment-1"
, links = Dict.fromList [ ( "self", "http://url-to-comment/1" ) ]
, content = "Comment 1"
, email = "[email protected]"
}
comment2 : Comment
comment2 =
{ id = "comment-2"
, links = Dict.fromList [ ( "self", "http://url-to-comment/2" ) ]
, content = "Comment 2"
, email = "[email protected]"
}
comment3 : Comment
comment3 =
{ id = "comment-3"
, links = Dict.fromList [ ( "self", "http://url-to-comment/3" ) ]
, content = "Comment 3"
, email = "[email protected]"
}
postToResource : Post -> ResourceInfo
postToResource post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
creatorToResource : Creator -> ResourceInfo
creatorToResource creator =
JsonApi.build "creators"
|> JsonApi.withId creator.id
|> JsonApi.withLinks creator.links
|> JsonApi.withAttributes
[ ( "firstname", string creator.firstname )
, ( "lastname", string creator.lastname )
]
commentRelationship : Comment -> ( String, ResourceInfo )
commentRelationship comment =
( comment.id, commentToResource comment )
commentToResource : Comment -> ResourceInfo
commentToResource comment =
JsonApi.build "comment"
|> JsonApi.withId comment.id
|> JsonApi.withLinks comment.links
|> JsonApi.withAttributes
[ ( "content", string comment.content )
, ( "email", string comment.email )
]
resources posts
Encodes a resource.