<h2 id="intro">Intro</h2>
<p>News and notifications are used in the game to let the players know something noteworthy has happened. It could be discovery of a new planet or construction project finally finishing.</p>
<p>All relevant information in the news is hyperlinked. If news mentions a planet, player can click the link and view current information of that planet.</p>
<h2 id="server-interface">Server interface</h2>
<p>Server has three resources for news, although we’re concentrating only one here:</p>
<pre><code>/api/message           ApiMessageR      GET POST
/api/message/#NewsId   ApiMessageIdR    DELETE
/api/icon              ApiMessageIcons  GET</code></pre>
<p>First one is for retrieving all messages and posting a new one. Second one is for marking one read and third one is for retrieving all icons that players can attach to messages written by them.</p>
<h2 id="database">Database</h2>
<p>Database is defined in /config/models file. For news, there’s only one table:</p>
<pre><code>News json
    content Text
    factionId FactionId
    date Int
    dismissed Bool
deriving Show Read Eq</code></pre>
<p>Content field contains the actual news article data as serialized JSON. This allows storing complex data, without having to have lots of columns or multiple tables.</p>
<h2 id="domain-objects">Domain objects</h2>
<p>There are many kinds of messages that players might see, but we’ll concentrate on one about discovering a new planet</p>
<p>All different kinds of articles are of same type: NewsArticle. Each different kind of article has their own value constructor (PlanetFound in this particular case). And each of those value constructors has single parameter of a specific type that holds information particular to that certain article (PlanetFoundNews in this case). Adding a new article means adding a new value constructor and record to hold the data.</p>
<pre><code>data NewsArticle =
    StarFound StarFoundNews
    | PlanetFound PlanetFoundNews
    | UserWritten UserWrittenNews
    | DesignCreated DesignCreatedNews
    | ConstructionFinished ConstructionFinishedNews


data PlanetFoundNews = PlanetFoundNews
    { planetFoundNewsPlanetName :: Text
    , planetFoundNewsSystemName :: Text
    , planetFoundNewsSystemId   :: Key StarSystem
    , planetFoundNewsPlanetId   :: Key Planet
    , planetFoundNewsDate       :: Int
    }</code></pre>
<p>Given a News object, we can turn it into NewsArticle. These are much nicer to deal with that densely packed News that is stored in database:</p>
<pre><code>parseNews :: News -&gt; Maybe NewsArticle
parseNews =
    decode . toLazyByteString . encodeUtf8Builder . newsContent</code></pre>
<p>Because parsing arbitrary JSON might fail, we get Maybe NewsArticle, instead of NewsArticle. It is possible to write the same code in longer way:</p>
<pre><code>parseNews news =
    let
        content = newsContent news
        utf8Encoded = encodeUtf8Builder content
        byteString = toLazyByteString utf8Encoded
    in
        decode byteString</code></pre>
<p>Similarly there’s two other functions for dealing with Entities (primary key, data - pair really) and list of Entities. Note that parseNewsEntities filters out all News that it didn’t manage to turn into NewsArticle. They have following signatures:</p>
<pre><code>parseNewsEntity :: Entity News -&gt; (Key News, Maybe NewsArticle)

parseNewsEntities :: [Entity News] -&gt; [(Key News, NewsArticle)]</code></pre>
<p>Writing JSON encoding and decoding is tedious, template Haskell can help us here:</p>
<pre><code>$(deriveJSON defaultOptions &#39;&#39;PlanetFoundNews)
$(deriveJSON defaultOptions &#39;&#39;NewsArticle)</code></pre>
<h2 id="turning-articles-into-json">Turning Articles into JSON</h2>
<p>News articles aren’t much use if they stay on the server, we need to send them to clients too. We can’t have multiple declarations of same typeclass for any type, so we declare complete new type and copy data there before turning it into JSON and sending to client (this is one way of doing this).</p>
<p>First step, define our types (concentrating on planet found news here):</p>
<pre><code>data NewsArticleDto =
    StarFoundDto StarFoundNewsDto
    | PlanetFoundDto PlanetFoundNewsDto
    | UserWrittenDto UserWrittenNewsDto
    | DesignCreatedDto DesignCreatedNewsDto
    | ConstructionFinishedDto ConstructionFinishedNewsDto
    deriving (Show, Read, Eq)

data PlanetFoundNewsDto = PlanetFoundNewsDto
    { planetFoundNewsDtoPlanetName :: Text
    , planetFoundNewsDtoSystemName :: Text
    , planetFoundNewsDtoSystemId   :: Key StarSystem
    , planetFoundNewsDtoPlanetId   :: Key Planet
    , planetFoundNewsDtoDate       :: Int
    }
    deriving (Show, Read, Eq)</code></pre>
<p>We need way to move data into dto and thus define a type class for that operation:</p>
<pre><code>class (ToJSON d) =&gt; ToDto c d | c -&gt; d where
    toDto :: c -&gt; d</code></pre>
<p>For more information about functional dependencies, check following links: <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-FunctionalDependencies" class="uri">https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-FunctionalDependencies</a> and <a href="https://wiki.haskell.org/Functional_dependencies" class="uri">https://wiki.haskell.org/Functional_dependencies</a></p>
<p>Writing instances for our type class:</p>
<pre><code>instance ToDto PlanetFoundNews PlanetFoundNewsDto where
    toDto news =
        PlanetFoundNewsDto { planetFoundNewsDtoPlanetName = planetFoundNewsPlanetName news
                           , planetFoundNewsDtoSystemName = planetFoundNewsSystemName news
                           , planetFoundNewsDtoSystemId = planetFoundNewsSystemId news
                           , planetFoundNewsDtoPlanetId = planetFoundNewsPlanetId news
                           , planetFoundNewsDtoDate = planetFoundNewsDate news
                           }

instance ToDto NewsArticle NewsArticleDto where
    toDto news =
        case news of
            (StarFound x) -&gt; StarFoundDto $ toDto x
            (PlanetFound x) -&gt; PlanetFoundDto $ toDto x
            (UserWritten x) -&gt; UserWrittenDto $ toDto x
            (DesignCreated x) -&gt; DesignCreatedDto $ toDto x
            (ConstructionFinished x) -&gt; ConstructionFinishedDto $ toDto x</code></pre>
<p>Finally, we want to wrap our news into something that has all the common info (id and link to icon to show)</p>
<pre><code>data NewsDto = NewsDto
    { newsDtoId    :: Key News
    , newsContents :: NewsArticleDto
    , newsIcon     :: Text
    }
    deriving (Show, Read, Eq)</code></pre>
<p>IconMapper knows how to turn NewsArticleDto (in this case) to corresponding link to the icon. Notice how our ToDto instance includes IconMapper in addition to Key and NewsArticle:</p>
<pre><code>instance ToDto ((Key News, NewsArticle), (IconMapper NewsArticleDto)) NewsDto where
    toDto ((nId, article), icons) =
        let
            content = toDto article
        in
        NewsDto { newsDtoId = nId
                , newsContents = content
                , newsIcon = runIconMapper icons content
                }</code></pre>
<h2 id="sideshow-iconmapper">Sideshow: IconMapper</h2>
<p>IconMapper is a function that knows how to retrieve url to icon that matches the given parameter (for example NewsArticleDto in this case):</p>
<pre><code>newtype IconMapper a =
    IconMapper { runIconMapper :: a -&gt; Text }</code></pre>
<p>One possible implementation that knows how to deal with NewsArticleDto. We have two levels of hierarchicy here, because UserNewsDto has special rules for figuring out which icon to use:</p>
<pre><code>iconMapper :: (Route App -&gt; Text) -&gt; IconMapper UserNewsIconDto -&gt; IconMapper NewsArticleDto
iconMapper render userIconMapper =
    IconMapper $ article -&gt;
        case article of
            PlanetFoundDto _-&gt;
                render $ StaticR images_news_planet_png

            UserWrittenDto details -&gt;
                runIconMapper userIconMapper $ userWrittenNewsDtoIcon details
    ...</code></pre>
<h2 id="back-to-json">Back to JSON</h2>
<p>I wrote ToJSON and FromJSON instances by hand, because I wanted full control on how the resulting JSON looks like. It’s possible to configure how template Haskell names fields for example, but I think that writing these out couple of times is good practice and makes sure that I understand what’s going on behind the scenes if I use template Haskell later.</p>
<pre><code>instance ToJSON NewsDto where
    toJSON (NewsDto { newsDtoId = nId
                    , newsContents = contents
                    , newsIcon = icon }) =
        object [ &quot;id&quot; .= nId
               , &quot;contents&quot; .= contents
               , &quot;tag&quot; .= jsonTag contents
               , &quot;icon&quot; .= icon
               , &quot;starDate&quot; .= newsStarDate contents
               ]

instance ToJSON PlanetFoundNewsDto where
    toJSON (PlanetFoundNewsDto { planetFoundNewsDtoPlanetName = pName
                               , planetFoundNewsDtoSystemId = sId
                               , planetFoundNewsDtoPlanetId = pId
                               , planetFoundNewsDtoSystemName = sName
                               }) =
        object [ &quot;planetName&quot; .= pName
               , &quot;systemName&quot; .= sName
               , &quot;planetId&quot; .= pId
               , &quot;systemId&quot; .= sId
               ]</code></pre>
<h2 id="time-to-put-it-all-together">Time to put it all together</h2>
<p>Handler function authenticates user, check they’re member of a faction and then loads all the news:</p>
<pre><code>getApiMessageR :: Handler Value
getApiMessageR = do
    (_, _, fId) &lt;- apiRequireFaction
    loadAllMessages fId</code></pre>
<p>Loading messages involves multiple steps:</p>
<ul>
<li>retrieve News from database
<ul>
<li>correct faction, not dismissed, sort by date</li>
</ul></li>
<li>parse them into ( Key News, NewsArticle )</li>
<li>get Url render function</li>
<li>create mapper for user icons</li>
<li>map all NewsArticles into ( NewsArticleDto, IconMapper )</li>
<li>turn them into JSON and return that to client</li>
</ul>
<pre><code>loadAllMessages :: Key Faction -&gt; HandlerFor App Value
loadAllMessages fId = do
    loadedMessages &lt;- runDB $ selectList [ NewsFactionId ==. fId
                                         , NewsDismissed ==. False ] [ Desc NewsDate ]
    let parsedMessages = parseNewsEntities loadedMessages
    render &lt;- getUrlRender
    let userIcons = userNewsIconMapper render
    return $ toJSON $ map (toDto . (flip (,) (iconMapper render userIcons))) parsedMessages</code></pre>
<p>
<a href="https://hackerpublicradio.org/eps/hpr2733/hpr2733.png"><img src="https://hackerpublicradio.org/eps/hpr2733/hpr2733-small.png" /></a>
</p>
