<h1 id="background">Background</h1>
<p>The space game I working on needs a admin interface that can by used by game masters to view and modify the simulation.</p>
<p>For start, I added interface for viewing, modifying and creating new people. It has three HTTP endpoints that are defined below. In this episode, I’ll concentrate on creating a new person and especially making sure that parameters used are valid.</p>
<pre><code>/api/admin/people              AdminApiPeopleR     GET
/api/admin/people/#PersonId    AdminApiPersonR     GET PUT
/api/admin/addPerson           AdminApiAddPersonR  POST</code></pre>
<h1 id="types-and-parsing">Types and parsing</h1>
<p>There are two important approaches on making sure that data is valid. Making illegal state unpresentable and parsing instead of validation.</p>
<p>If it’s impossible to create invalid data, you don’t have to validate it. Instead of using <code>Integer</code> and checking that given parameter is 0 or more, you should use <code>Natural</code>. Since <code>Natural</code> can’t have negative values, you don’t have to validate it. Similarly, instead of using a list, you could use <code>NonEmpty</code> to make sure that there’s at least one element present in the collection.</p>
<p>Parse, don’t validate is similar approach. Instead of having a lax parser and then validating the result, parser should reject data that doesn’t make sense. By selecting suitable datatypes to represent data in the system, simply parsing incoming message is sometimes enough to validate it at the same time.</p>
<h1 id="person-creation">Person creation</h1>
<p>Function in charge of generating a new person has signature of <code>generatePersonM :: RandomGen g =&gt; StarDate -&gt; PersonOptions -&gt; Rand g Person</code>. Given a current <code>StarDate</code> and <code>PersonOptions</code> describing what kind of person is needed, it will return a computation that can be executed to generate a random person.</p>
<p><code>PersonOptions</code> is very barebones. There’s only one field to tell what kind of age the person should have and even that is an optional field.</p>
<pre><code>data PersonOptions = PersonOptions
    { personOptionsAge :: Maybe AgeOptions
    } deriving (Show, Read, Eq)</code></pre>
<p><code>AgeOptions</code> has two possibilities. <code>AgeBracket</code> describes case where age should be inside of given range. <code>ExactAge</code> specifies exactly what age should be.</p>
<pre><code>data AgeOptions =
    AgeBracket Age Age
    | ExactAge Age
    deriving (Show, Read, Eq)</code></pre>
<p><code>Age</code> is newtype wrapping <code>Natural</code>, thus <code>Age</code> can never be less than zero.</p>
<pre><code>newtype Age = Age { unAge :: Natural }
    deriving (Show, Read, Eq, Num, Ord)</code></pre>
<p>Hand written <code>FromJSON</code> instance takes care of rejecting numbers that aren’t integers and at least zero. One could skip the checks here and parsed <code>Age</code> still couldn’t be negative. Advantage of explicit checks is that we get much nicer error message instead of just annoying runtime exception.</p>
<pre><code>instance FromJSON Age where
    parseJSON =
        withScientific &quot;age&quot;
            (\x -&gt; case toBoundedInteger x of
                Nothing -&gt;
                    mempty

                Just n -&gt;
                    if n &gt;= 0 then
                        return $ Age $ fromIntegral (n :: Int)

                    else
                        mempty)</code></pre>
<p>So, when creating a new person, you can have:</p>
<ul>
<li>no age options at all, computer can pick something</li>
<li>specific age, computer calculates date of birth based on current date</li>
<li>age bracket, computer calculates date of birth based on current date and bracket</li>
<li>age is always integer that is 0 or more</li>
</ul>
<p>There’s still possibility of error. Nothing ensure that age bracket makes sense. It could be <code>AgeBracket (Age 10) (Age 5)</code> (bracket from 10 to 5). We need to add a bit of validation.</p>
<p><code>Data.Validation</code> is “a data-type like Either but with an accumulating Applicative”. What this means to me is that I can validate multiple aspects and collect errors in a list. It’s handy for getting all the problems at once, instead of having to fix them one by one and retry after each fix.</p>
<p>Our validation function has signature <code>validateAddPerson :: PersonOptions -&gt; Validation [ErrorCode] PersonOptions</code>. Given <code>PersonOptions</code>, it will give list of <code>ErrorCode</code> and original <code>PersonOptions</code>. Multiple validation functions can be combined for more complex validations.</p>
<p>In our example <code>validateAgeOptions</code> validates only age related options of the data. <code>validateAddPerson</code> is supposed to validate whole data, but currently it just delegates to <code>validateAgeOptions</code>. In the future, we can add more validations by adding more functions and chaining them with <code>&lt;*</code> operator.</p>
<pre><code>validateAddPerson :: PersonOptions -&gt; Validation [ErrorCode] PersonOptions
validateAddPerson opt =
        pure opt
            &lt;* validateAgeOptions opt

validateAgeOptions :: PersonOptions -&gt; Validation [ErrorCode] PersonOptions
validateAgeOptions opt =
    case personOptionsAge opt of
        Nothing -&gt;
            _Success # opt

        Just (AgeBracket a b) -&gt;
            if a &lt;= b
                then _Success # opt
                else _Failure # [ AgeBracketStartIsGreaterThanEnd ]

        Just (ExactAge _) -&gt;
            _Success # opt</code></pre>
<h1 id="putting-it-all-together">Putting it all together</h1>
<p>Function that handles <code>POST</code> message and creates a new person is shown below:</p>
<pre><code>postAdminApiAddPersonR :: Handler Value
postAdminApiAddPersonR = do
    _ &lt;- apiRequireAdmin
    msg &lt;- requireJsonBody
    date &lt;- runDB $ starDate
    _ &lt;- raiseIfFailure $ validateAddPerson msg
    g &lt;- liftIO newStdGen
    let person = evalRand (generatePersonM date msg) g
    pId &lt;- runDB $ insert person
    returnJson (Entity pId person)</code></pre>
<p>It does several things: - check that current user is admin - get json content and parse it to <code>PersonOptions</code> - get current star date from database - validate <code>PersonOptions</code> and return error if validation fails - get new random number generator - generate new person - insert it into database - return tuple of <code>(PersonId, Person)</code></p>
<h1 id="closing">Closing</h1>
<p>Types should represent only valid states. By having invalid state unpresentable, we can avoid many errors. Likewise, parsing should reject invalid data. This usually follows from having invalid states being unpresentable (you can’t parse invalid message to invalid data if you don’t have way to represent that invalid data).</p>
<p>Questions, comments and feedback welcome. Best way to reach me is either by email or in mastodon, where I’m <code>Tuula@mastodon.social</code>.</p>
