...

/

Creating our User with Lifting

Creating our User with Lifting

Learn how to create a user for our User Registration project.

We'll cover the following...

Overview

Let’s assume our data passed the checks mentioned in the previous lesson and is deemed valid. We should start building our User domain object now. For the first and last name, this is pretty easy. Use the iso we saw earlier and wrap our string in it. For gender, we use one of the various ways of asserting that the sex string is a valid Gender because we (but not the compiler) now know it’s OK. Age and country pose some difficulties. If we want to get a PositiveInteger for age, fp-ts will give us back an Option. Plus, we didn’t do any checks for the region. What if it happens to be invalid? Exploring this topic, we add the following functions to our domain:

Press + to interact
import * as O from 'fp-ts/lib/Option';
export type CreateUser = (f: FirstName,
l: LastName,
a: PositiveInteger,
g: Gender,
r: Region) => User;
export type FindRegion = (country: string) => O.Option<Region>;
export type FindGender = (sex: string) => O.Option<Gender>;
  • Lines 3–7: We keep CreateUser clean, that is, the incoming values aren’t Options that we have to check within the function. The only concern is creating a user from validated inputs. Creating an object in one go is recommended in TypeScript.
  • Lines 9–10: For region and gender, we play it safe and return the right types within an Optional value. In addition, we’ll use a built-in method for retrieving the positive integer, which also returns an Option.

We could’ve passed optionals into CreateUser, but that would involve many dirty checks. So we want to avoid that result if possible. But first, we have to discuss the concept of lifting.

We have other ways to handle the issue of creating the User. We can add checks to ensure that the region is acceptable, and with validation, we can pass multiple correct values to a follow-up function through the map. But remember, even after checking external data, there might be some calls we must make ...