Created
April 22, 2016 19:36
-
-
Save 5outh/c35888405566fc638466cae0760d7fd3 to your computer and use it in GitHub Desktop.
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
-- For example | |
type JSON = Text | |
-- An instance of RenderResponse knows how to turn itself into JSON | |
class RenderResponse a where | |
render :: a -> JSON | |
data Error = Error Text | |
data RegularResponse = RegularResponse Text -- For example | |
data ErrorResponse a = ErrorResponse a [Error] -- Parameterize over Response type | |
-- We know how to render a regular response | |
instance RenderResponse RegularResponse where | |
render (RegularResponse text) = "{ \"message\":" <> text <> " }" | |
-- We know how to render an error | |
instance RenderResponse Error | |
render (Error text) = "{ \"error\":" <> text <> " }" | |
-- If we know how to render the response, we know how to render it with errors | |
instance (RenderResponse a) => RenderResponse (ErrorResponse a) | |
render (ErrorResponse response errors) = "{ \"data\": " <> render response <> ", \"errors\": " <> errors_ <> " }" | |
where errors_ = mconcat (map render errors) | |
-- render (ErrorResponse "response" ["IT BROKE"]) | |
-- { "data": {"message": "response"}, "errors": [{ "error": "IT BROKE" }] } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment