Writing a Simple REST Web Service in PureScript - Part 1

23 minute read

At Nilenso, we’ve been working with a client who has chosen PureScript as their primary programming language. Since I couldn’t find any canonical documentation on writing a web service in PureScript, I thought I’d jot down the approach that we took.

The aim of this two-part tutorial is to create a simple JSON REST web service written in PureScript, to run on a node.js server. This assumes that you have basic proficiency with PureScript. We have the following requirements:

  1. persisting users into a Postgres database.
  2. API endpoints for creating, updating, getting, listing and deleting users.
  3. validation of API requests.
  4. reading the server and database configs from environment variables.
  5. logging HTTP requests and debugging info.

In this part we’ll work on setting up the project and on the first two requirements. In the next part we’ll work on the rest of the requirements.

Setting Up

We start with installing PureScript and the required tools. This assumes that we have node and npm installed on our machine.

$ mkdir -p ~/.local/
$ npm install -g purescript pulp bower --prefix ~/.local/

Pulp is a build tool for PureScript projects and bower is a package manager used to get PureScript libraries. We’ll have to add ~/.local/bin in our $PATH (if it is not already added) to access the binaries installed.

Let’s create a directory for our project and make Pulp initialize it:

$ mkdir ps-simple-rest-service
$ cd ps-simple-rest-service
$ pulp init
$ ls
bower.json  bower_components  src  test
$ cat bower.json
{
  "name": "ps-simple-rest-service",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "output"
  ],
  "dependencies": {
    "purescript-prelude": "^3.1.0",
    "purescript-console": "^3.0.0"
  },
  "devDependencies": {
    "purescript-psci-support": "^3.0.0"
  }
}
$ ls bower_components
purescript-console  purescript-eff  purescript-prelude purescript-psci-support

Pulp creates the basic project structure for us. src directory will contain the source while the test directory will contain the tests. bower.json contains the PureScript libraries as dependencies which are downloaded and installed in the bower_components directory.

Types First

First, we create the types needed in src/SimpleService/Types.purs:

module SimpleService.Types where

import Prelude

import Data.Foreign.Class (class Decode, class Encode)
import Data.Foreign.Generic (defaultOptions, genericDecode, genericEncode)
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Show (genericShow)

type UserID = Int

newtype User = User
  { id   :: UserID
  , name :: String
  }

derive instance genericUser :: Generic User _

instance showUser :: Show User where
  show = genericShow

instance decodeUser :: Decode User where
  decode = genericDecode $ defaultOptions { unwrapSingleConstructors = true }

instance encodeUser :: Encode User where
  encode = genericEncode $ defaultOptions { unwrapSingleConstructors = true }

We are using the generic support for PureScript types from the purescript-generics-rep and purescript-foreign-generic libraries to encode and decode the User type to JSON. We install the library by running the following command:

$ bower install purescript-foreign-generic --save

Now we can load up the module in the PureScript REPL and try out the JSON conversion features:

$ pulp repl
> import SimpleService.Types
> user = User { id: 1, name: "Abhinav"}
> user
(User { id: 1, name: "Abhinav" })

> import Data.Foreign.Generic
> userJSON = encodeJSON user
> userJSON
"{\"name\":\"Abhinav\",\"id\":1}"

> import Data.Foreign
> import Control.Monad.Except.Trans
> import Data.Identity
> dUser = decodeJSON userJSON :: F User
> eUser = let (Identity eUser) = runExceptT $ dUser in eUser
> eUser
(Right (User { id: 1, name: "Abhinav" }))

We use encodeJSON and decodeJSON functions from the Data.Foreign.Generic module to encode and decode the User instance to JSON. The return type of decodeJSON is a bit complicated as it needs to return the parsing errors too. In this case, the decoding returns no errors and we get back a Right with the correctly parsed User instance.

Persisting It

Next, we add the support for saving a User instance to a Postgres DB. First, we install the required libraries using bower and npm: pg for Javascript bindings to call Postgres, purescript-aff for asynchronous processing and purescript-postgresql-client for PureScript wrapper over pg:

$ npm init -y
$ npm install pg@6.4.0 --save
$ bower install purescript-aff --save
$ bower install purescript-postgresql-client --save

Before writing the code, we create the database and the users table using the command-line Postgres client:

$ psql postgres
psql (9.5.4)
Type "help" for help.

postgres=# create database simple_service;
CREATE DATABASE
postgres=# \c simple_service
You are now connected to database "simple_service" as user "abhinav".
simple_service=# create table users (id int primary key, name varchar(100) not null);
CREATE TABLE
simple_service=# \d users
            Table "public.users"
 Column |          Type          | Modifiers
--------+------------------------+-----------
 id     | integer                | not null
 name   | character varying(100) | not null
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)

Now we add support for converting a User instance to-and-from an SQL row by adding the following code in the src/SimpleService/Types.purs file:

import Data.Array as Array
import Data.Either (Either(..))
import Database.PostgreSQL (class FromSQLRow, class ToSQLRow, fromSQLValue, toSQLValue)

-- code written earlier

instance userFromSQLRow :: FromSQLRow User where
  fromSQLRow [id, name] =
    User <$> ({ id: _, name: _} <$> fromSQLValue id <*> fromSQLValue name)

  fromSQLRow xs = Left $ "Row has " <> show n <> " fields, expecting 2."
    where n = Array.length xs

instance userToSQLRow :: ToSQLRow User where
  toSQLRow (User {id, name}) = [toSQLValue id, toSQLValue name]

We can try out the persistence support in the REPL:

$ pulp repl
PSCi, version 0.11.6
Type :? for help

import Prelude
>
> import SimpleService.Types
> import Control.Monad.Aff (launchAff, liftEff')
> import Database.PostgreSQL as PG
> user = User { id: 1, name: "Abhinav" }
> databaseConfig = {user: "abhinav", password: "", host: "localhost", port: 5432, database: "simple_service", max: 10, idleTimeoutMillis: 1000}

> :paste
… void $ launchAff do
…   pool <- PG.newPool databaseConfig
…   PG.withConnection pool $ \conn -> do
…     PG.execute conn (PG.Query "insert into users (id, name) values ($1, $2)") user
…
unit

> import Data.Foldable (for_)
> import Control.Monad.Eff.Console (logShow)
> :paste
… void $ launchAff do
…   pool <- PG.newPool databaseConfig
…   PG.withConnection pool $ \conn -> do     users :: Array User <- PG.query conn (PG.Query "select id, name from users where id = $1") (PG.Row1 1)
…     liftEff' $ void $ for_ users logShow
…
unit
(User { id: 1, name: "Abhinav" })

We create the databaseConfig record with the configs needed to connect to the database. Using the recond, we create a new Postgres connection pool (PG.newPool) and get a connection from it (PG.withConnection). We call PG.execute with the connection, the SQL insert query for the users table and the User instance, to insert the user into the table. All of this is done inside launchAff which takes care of sequencing the callbacks correctly to make the asynchronous code look synchronous.

Similarly, in the second part, we query the table using PG.query function by calling it with a connection, the SQL select query and the User ID as the query parameter. It returns an Array of users which we log to the console using the logShow function.

We use this experiment to write the persistence related code in the src/SimpleService/Persistence.purs file:

module SimpleService.Persistence
  ( insertUser
  , findUser
  , updateUser
  , deleteUser
  , listUsers
  ) where

import Prelude

import Control.Monad.Aff (Aff)
import Data.Array as Array
import Data.Maybe (Maybe)
import Database.PostgreSQL as PG
import SimpleService.Types (User(..), UserID)

insertUserQuery :: String
insertUserQuery = "insert into users (id, name) values ($1, $2)"

findUserQuery :: String
findUserQuery = "select id, name from users where id = $1"

updateUserQuery :: String
updateUserQuery = "update users set name = $1 where id = $2"

deleteUserQuery :: String
deleteUserQuery = "delete from users where id = $1"

listUsersQuery :: String
listUsersQuery = "select id, name from users"

insertUser :: forall eff. PG.Connection -> User
           -> Aff (postgreSQL :: PG.POSTGRESQL | eff) Unit
insertUser conn user =
  PG.execute conn (PG.Query insertUserQuery) user

findUser :: forall eff. PG.Connection -> UserID
         -> Aff (postgreSQL :: PG.POSTGRESQL | eff) (Maybe User)
findUser conn userID =
  map Array.head $ PG.query conn (PG.Query findUserQuery) (PG.Row1 userID)

updateUser :: forall eff. PG.Connection -> User
           -> Aff (postgreSQL :: PG.POSTGRESQL | eff) Unit
updateUser conn (User {id, name}) =
  PG.execute conn (PG.Query updateUserQuery) (PG.Row2 name id)

deleteUser :: forall eff. PG.Connection -> UserID
           -> Aff (postgreSQL :: PG.POSTGRESQL | eff) Unit
deleteUser conn userID =
  PG.execute conn (PG.Query deleteUserQuery) (PG.Row1 userID)

listUsers :: forall eff. PG.Connection
          -> Aff (postgreSQL :: PG.POSTGRESQL | eff) (Array User)
listUsers conn =
  PG.query conn (PG.Query listUsersQuery) PG.Row0

Serving It

We can now write a simple HTTP API over the persistence layer using Express to provide CRUD functionality for users. Let’s install Express and purescript-express, the PureScript wrapper over it:

$ npm install express --save
$ bower install purescript-express --save

Getting a User

We do this top-down. First, we change src/Main.purs to run the HTTP server by providing the server port and database configuration:

module Main where

import Prelude

import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Console (CONSOLE)
import Database.PostgreSQL as PG
import Node.Express.Types (EXPRESS)
import SimpleService.Server (runServer)

main :: forall eff. Eff ( console :: CONSOLE
                        , express :: EXPRESS
                        , postgreSQL :: PG.POSTGRESQL
                        | eff) Unit
main = runServer port databaseConfig
  where
    port = 4000
    databaseConfig = { user: "abhinav"
                     , password: ""
                     , host: "localhost"
                     , port: 5432
                     , database: "simple_service"
                     , max: 10
                     , idleTimeoutMillis: 1000
                     }

Next, we wire up the server routes to the handlers in src/SimpleService/Server.purs:

module SimpleService.Server (runServer) where

import Prelude

import Control.Monad.Aff (runAff)
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Class (liftEff)
import Control.Monad.Eff.Console (CONSOLE, log, logShow)
import Database.PostgreSQL as PG
import Node.Express.App (App, get, listenHttp)
import Node.Express.Types (EXPRESS)
import SimpleService.Handler (getUser)

app :: forall eff. PG.Pool -> App (postgreSQL :: PG.POSTGRESQL | eff)
app pool = do
  get "/v1/user/:id" $ getUser pool

runServer :: forall eff.
             Int
          -> PG.PoolConfiguration
          -> Eff ( express :: EXPRESS
                 , postgreSQL :: PG.POSTGRESQL
                 , console :: CONSOLE
                 | eff ) Unit
runServer port databaseConfig =  void $ runAff logShow pure do
  pool <- PG.newPool databaseConfig
  let app' = app pool
  void $ liftEff $ listenHttp app' port \_ -> log $ "Server listening on :" <> show port

runServer creates a PostgreSQL connection pool and passes it to the app function which creates the Express application, which in turn, binds it to the handler getUser. Then it launches the HTTP server by calling listenHttp.

Finally, we write the actual getUser handler in src/SimpleService/Handler.purs:

module SimpleService.Handler where

import Prelude

import Control.Monad.Aff.Class (liftAff)
import Data.Foreign.Class (encode)
import Data.Int (fromString)
import Data.Maybe (Maybe(..))
import Database.PostgreSQL as PG
import Node.Express.Handler (Handler)
import Node.Express.Request (getRouteParam)
import Node.Express.Response (end, sendJson, setStatus)
import SimpleService.Persistence as P

getUser :: forall eff. PG.Pool -> Handler (postgreSQL :: PG.POSTGRESQL | eff)
getUser pool = getRouteParam "id" >>= case _ of
  Nothing -> respond 422 { error: "User ID is required" }
  Just sUserId -> case fromString sUserId of
    Nothing -> respond 422 { error: "User ID must be an integer: " <> sUserId }
    Just userId -> liftAff (PG.withConnection pool $ flip P.findUser userId) >>= case _ of
      Nothing -> respond 404 { error: "User not found with id: " <> sUserId }
      Just user -> respond 200 (encode user)

respond :: forall eff a. Int -> a -> Handler eff
respond status body = do
  setStatus status
  sendJson body

respondNoContent :: forall eff. Int -> Handler eff
respondNoContent status = do
  setStatus status
  end

getUser validates the route parameter for valid user ID, sending error HTTP responses in case of failures. It then calls findUser to find the user and returns appropriate response.

We can test this on the command-line using HTTPie. We run pulp --watch run in one terminal to start the server with file watching, and test it from another terminal:

$ pulp --watch run
* Building project in ps-simple-rest-service
* Build successful.
Server listening on :4000
$ http GET http://localhost:4000/v1/user/1 # should return the user we created earlier
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 25
Content-Type: application/json; charset=utf-8
Date: Sun, 10 Sep 2017 14:32:52 GMT
ETag: W/"19-qmtK9XY+WDrqHTgqtFlV+h+NGOY"
X-Powered-By: Express

{
    "id": 1,
    "name": "Abhinav"
}
$ http GET http://localhost:4000/v1/user/s
HTTP/1.1 422 Unprocessable Entity
Connection: keep-alive
Content-Length: 38
Content-Type: application/json; charset=utf-8
Date: Sun, 10 Sep 2017 14:36:04 GMT
ETag: W/"26-//tvORl1gGDUMwgSaqbEpJhuadI"
X-Powered-By: Express

{
    "error": "User ID must be an integer: s"
}
$ http GET http://localhost:4000/v1/user/2
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 36
Content-Type: application/json; charset=utf-8
Date: Sun, 10 Sep 2017 14:36:11 GMT
ETag: W/"24-IyD5VT4E8/m3kvpwycRBQunI7Uc"
X-Powered-By: Express

{
    "error": "User not found with id: 2"
}

Deleting a User

deleteUser handler is similar. We add the route in the app function in the src/SimpleService/Server.purs file:

-- previous code
import Node.Express.App (App, delete, get, listenHttp)
import SimpleService.Handler (deleteUser, getUser)
-- previous code

app :: forall eff. PG.Pool -> App (postgreSQL :: PG.POSTGRESQL | eff)
app pool = do
  get "/v1/user/:id" $ getUser pool
  delete "/v1/user/:id" $ deleteUser pool

-- previous code

And we add the handler in the src/SimpleService/Handler.purs file:

deleteUser :: forall eff. PG.Pool -> Handler (postgreSQL :: PG.POSTGRESQL | eff)
deleteUser pool = getRouteParam "id" >>= case _ of
  Nothing -> respond 422 { error: "User ID is required" }
  Just sUserId -> case fromString sUserId of
    Nothing -> respond 422 { error: "User ID must be an integer: " <> sUserId }
    Just userId -> do
      found <- liftAff $ PG.withConnection pool \conn -> PG.withTransaction conn do
        P.findUser conn userId >>= case _ of
          Nothing -> pure false
          Just _  -> do
            P.deleteUser conn userId
            pure true
      if found
        then respondNoContent 204
        else respond 404 { error: "User not found with id: " <> sUserId }

After the usual validations on the route param, deleteUser tries to find the user by the given user ID and if found, it deletes the user. Both the persistence related functions are run inside a single SQL transaction using PG.withTransaction function. deleteUser return 404 status if the user is not found, else it returns 204 status.

Let’s try it out:

$ http GET http://localhost:4000/v1/user/1
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 25
Content-Type: application/json; charset=utf-8
Date: Mon, 11 Sep 2017 05:10:50 GMT
ETag: W/"19-GC9FAtbd81t7CtrQgsNuc8HITXU"
X-Powered-By: Express

{
    "id": 1,
    "name": "Abhinav"
}
$ http DELETE http://localhost:4000/v1/user/1
HTTP/1.1 204 No Content
Connection: keep-alive
Date: Mon, 11 Sep 2017 05:10:56 GMT
X-Powered-By: Express
$ http GET http://localhost:4000/v1/user/1
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 37
Content-Type: application/json; charset=utf-8
Date: Mon, 11 Sep 2017 05:11:03 GMT
ETag: W/"25-Eoc4ZbEF73CyW8EGh6t2jqI8mLU"
X-Powered-By: Express

{
    "error": "User not found with id: 1"
}
$ http DELETE http://localhost:4000/v1/user/1
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 37
Content-Type: application/json; charset=utf-8
Date: Mon, 11 Sep 2017 05:11:05 GMT
ETag: W/"25-Eoc4ZbEF73CyW8EGh6t2jqI8mLU"
X-Powered-By: Express

{
    "error": "User not found with id: 1"
}

Creating a User

createUser handler is a bit more involved. First, we add an Express middleware to parse the body of the request as JSON. We use body-parser for this and access it through PureScript FFI. We create a new file src/SimpleService/Middleware/BodyParser.js with the content:

"use strict";

var bodyParser = require("body-parser");

exports.jsonBodyParser = bodyParser.json({
  limit: "5mb"
});

And write a wrapper for it in the file src/SimpleService/Middleware/BodyParser.purs with the content:

module SimpleService.Middleware.BodyParser where

import Prelude
import Data.Function.Uncurried (Fn3)
import Node.Express.Types (ExpressM, Response, Request)

foreign import jsonBodyParser ::
  forall e. Fn3 Request Response (ExpressM e Unit) (ExpressM e Unit)

We also install the body-parser npm dependency:

$ npm install --save body-parser

Next, we change the app function in the src/SimpleService/Server.purs file to add the middleware and the route:

-- previous code
import Node.Express.App (App, delete, get, listenHttp, post, useExternal)
import SimpleService.Handler (createUser, deleteUser, getUser)
import SimpleService.Middleware.BodyParser (jsonBodyParser)
-- previous code

app :: forall eff. PG.Pool -> App (postgreSQL :: PG.POSTGRESQL | eff)
app pool = do
  useExternal jsonBodyParser

  get "/v1/user/:id" $ getUser pool
  delete "/v1/user/:id" $ deleteUser pool
  post "/v1/users" $ createUser pool

And finally, we write the handler in the src/SimpleService/Handler.purs file:

-- previous code
import Data.Either (Either(..))
import Data.Foldable (intercalate)
import Data.Foreign (renderForeignError)
import Node.Express.Request (getBody, getRouteParam)
import SimpleService.Types
-- previous code

createUser :: forall eff. PG.Pool -> Handler (postgreSQL :: PG.POSTGRESQL | eff)
createUser pool = getBody >>= case _ of
  Left errs -> respond 422 { error: intercalate ", " $ map renderForeignError errs}
  Right u@(User user) ->
    if user.id <= 0
      then respond 422 { error: "User ID must be positive: " <> show user.id}
      else if user.name == ""
        then respond 422 { error: "User name must not be empty" }
        else do
          liftAff (PG.withConnection pool $ flip P.insertUser u)
          respondNoContent 201

createUser calls getBody which has type signature forall e a. (Decode a) => HandlerM (express :: EXPRESS | e) (Either MultipleErrors a). It returns either a list of parsing errors or a parsed instance, which in our case, is a User. In case of errors, we just return the errors rendered as string with a 422 status. If we get a parsed User instance, we do some validations on it, returning appropriate error messages. If all validations pass, we create the user in the DB by calling insertUser from the persistence layer and respond with a status 201.

We can try it out:

$ http POST http://localhost:4000/v1/users name="abhinav"
HTTP/1.1 422 Unprocessable Entity
Connection: keep-alive
Content-Length: 97
Content-Type: application/json; charset=utf-8
Date: Mon, 11 Sep 2017 05:51:28 GMT
ETag: W/"61-BgsrMukZpImcdwAJEKCZ+70WBb8"
X-Powered-By: Express

{
    "error": "Error at array index 0: (ErrorAtProperty \"id\" (TypeMismatch \"Int\" \"Undefined\"))"
}
$ http POST http://localhost:4000/v1/users id:=1 name=""
HTTP/1.1 422 Unprocessable Entity
Connection: keep-alive
Content-Length: 39
Content-Type: application/json; charset=utf-8
Date: Mon, 11 Sep 2017 05:51:42 GMT
ETag: W/"27-JQsh12xu/rEFdWy8REF4NMtBUB4"
X-Powered-By: Express

{
    "error": "User name must not be empty"
}
$ http POST http://localhost:4000/v1/users id:=1 name="abhinav"
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 0
Date: Mon, 11 Sep 2017 05:52:23 GMT
X-Powered-By: Express
$ http GET http://localhost:4000/v1/user/1
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 25
Content-Type: application/json; charset=utf-8
Date: Mon, 11 Sep 2017 05:52:30 GMT
ETag: W/"19-GC9FAtbd81t7CtrQgsNuc8HITXU"
X-Powered-By: Express

{
    "id": 1,
    "name": "abhinav"
}

First try returns a parsing failure because we didn’t provide the id field. Second try is a validation failure because the name was empty. Third try is a success which we check by doing a GET request next.

Updating a User

We want to allow a user’s name to be updated through the API, but not the user’s id. So we add a new type to src/SimpleService/Types.purs to represent a possible change in user’s name:

-- previous code
import Data.Foreign.NullOrUndefined (NullOrUndefined)
-- previous code

newtype UserPatch = UserPatch { name :: NullOrUndefined String }

derive instance genericUserPatch :: Generic UserPatch _

instance decodeUserPatch :: Decode UserPatch where
  decode = genericDecode $ defaultOptions { unwrapSingleConstructors = true }

NullOrUndefined is a wrapper over Maybe with added support for Javascript null and undefined values. We define UserPatch as having a possibly null (or undefined) name field.

Now we can add the corresponding handler in src/SimpleService/Handlers.purs:

-- previous code
import Data.Foreign.NullOrUndefined (unNullOrUndefined)
-- previous code

updateUser :: forall eff. PG.Pool -> Handler (postgreSQL :: PG.POSTGRESQL | eff)
updateUser pool = getRouteParam "id" >>= case _ of
  Nothing -> respond 422 { error: "User ID is required" }
  Just sUserId -> case fromString sUserId of
    Nothing -> respond 422 { error: "User ID must be positive: " <> sUserId }
    Just userId -> getBody >>= case _ of
      Left errs -> respond 422 { error: intercalate ", " $ map renderForeignError errs}
      Right (UserPatch userPatch) -> case unNullOrUndefined userPatch.name of
        Nothing -> respondNoContent 204
        Just userName -> if userName == ""
          then respond 422 { error: "User name must not be empty" }
          else do
            savedUser <- liftAff $ PG.withConnection pool \conn -> PG.withTransaction conn do
              P.findUser conn userId >>= case _ of
                Nothing -> pure Nothing
                Just (User user) -> do
                  let user' = User (user { name = userName })
                  P.updateUser conn user'
                  pure $ Just user'
            case savedUser of
              Nothing -> respond 404 { error: "User not found with id: " <> sUserId }
              Just user -> respond 200 (encode user)

After checking for a valid user ID as before, we get the decoded request body as a UserPatch instance. If the path does not have the name field or has it as null, there is nothing to do and we respond with a 204 status. If the user name is present in the patch, we validate it for non-emptiness. Then, within a DB transaction, we try to find the user with the given ID, responding with a 404 status if the user is not found. If the user is found, we update the user’s name in the database, and respond with a 200 status and the saved user encoded as the JSON response body.

Finally, we can add the route to our server’s router in src/SimpleService/Server.purs to make the functionality available:

-- previous code
import Node.Express.App (App, delete, get, http, listenHttp, post, useExternal)
import Node.Express.Types (EXPRESS, Method(..))
import SimpleService.Handler (createUser, deleteUser, getUser, updateUser)
-- previous code

app :: forall eff. PG.Pool -> App (postgreSQL :: PG.POSTGRESQL | eff)
app pool = do
  useExternal jsonBodyParser

  get "/v1/user/:id"    $ getUser pool
  delete "/v1/user/:id" $ deleteUser pool
  post "/v1/users"      $ createUser pool
  patch "/v1/user/:id"  $ updateUser pool
  where
    patch = http (CustomMethod "patch")

We can try it out now:

$ http GET http://localhost:4000/v1/user/1
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 26
Content-Type: application/json; charset=utf-8
Date: Fri, 11 Sep 2017 06:41:10 GMT
ETag: W/"1a-hoLBx55zeY8nZFWJh/kM05pXwSA"
X-Powered-By: Express

{
    "id": 1,
    "name": "abhinav"
}
$ http PATCH http://localhost:4000/v1/user/1 name=abhinavsarkar
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 31
Content-Type: application/json; charset=utf-8
Date: Fri, 11 Sep 2017 06:41:36 GMT
ETag: W/"1f-EG5i0hq/hYhF0BsuheD9hNXeBpI"
X-Powered-By: Express

{
    "id": 1,
    "name": "abhinavsarkar"
}
$ http GET http://localhost:4000/v1/user/1
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 31
Content-Type: application/json; charset=utf-8
Date: Fri, 11 Sep 2017 06:41:40 GMT
ETag: W/"1f-EG5i0hq/hYhF0BsuheD9hNXeBpI"
X-Powered-By: Express

{
    "id": 1,
    "name": "abhinavsarkar"
}
$ http PATCH http://localhost:4000/v1/user/1
HTTP/1.1 204 No Content
Connection: keep-alive
Date: Fri, 11 Sep 2017 06:42:31 GMT
X-Powered-By: Express
$ http PATCH http://localhost:4000/v1/user/1 name=""
HTTP/1.1 422 Unprocessable Entity
Connection: keep-alive
Content-Length: 39
Content-Type: application/json; charset=utf-8
Date: Fri, 11 Sep 2017 06:43:17 GMT
ETag: W/"27-JQsh12xu/rEFdWy8REF4NMtBUB4"
X-Powered-By: Express

{
    "error": "User name must not be empty"
}

Listing all Users

Listing all users is quite simple since it doesn’t require us to take any request parameter.

We add the handler to the src/SimpleService/Handler.purs file:

-- previous code
listUsers :: forall eff. PG.Pool -> Handler (postgreSQL :: PG.POSTGRESQL | eff)
listUsers pool = liftAff (PG.withConnection pool P.listUsers) >>= encode >>> respond 200

And the route to the src/SimpleService/Server.purs file:

-- previous code
import SimpleService.Handler (createUser, deleteUser, getUser, listUsers, updateUser)
-- previous code

app :: forall eff. PG.Pool -> App (postgreSQL :: PG.POSTGRESQL | eff)
app pool = do
  useExternal jsonBodyParser

  get "/v1/user/:id"    $ getUser pool
  delete "/v1/user/:id" $ deleteUser pool
  post "/v1/users"      $ createUser pool
  patch "/v1/user/:id"  $ updateUser pool
  get "/v1/users"       $ listUsers pool
  where
    patch = http (CustomMethod "patch")

And that’s it. We can test this endpoint:

$ http POST http://localhost:4000/v1/users id:=2 name=sarkarabhinav
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 0
Date: Fri, 11 Sep 2017 07:06:24 GMT
X-Powered-By: Express
$ http GET http://localhost:4000/v1/users
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 65
Content-Type: application/json; charset=utf-8
Date: Fri, 11 Sep 2017 07:06:27 GMT
ETag: W/"41-btt9uNdG+9A1RO7SCLOsyMmIyFo"
X-Powered-By: Express

[
    {
        "id": 1,
        "name": "abhinavsarkar"
    },
    {
        "id": 2,
        "name": "sarkarabhinav"
    }
]

Conclusion

That concludes the first part of the two-part tutorial. We learned how to set up a PureScript project, how to access a Postgres database and how to create a JSON REST API over the database. The code till the end of this part can be found in github. In the next part, we’ll learn how to do API validation, application configuration and logging. This post can be discussed on r/purescript.

If you liked this post, please leave a comment.

Original post by Abhinav Sarkar - check out All posts on abhinavsarkar.net

Gunak — Designing with the Indian Government

Working with a government body to digitise their offline hospital quality assurance system

What’s the problem?

The NRHM (National Rural Health Mission) is an initiative undertaken by the Government of India to address the health needs of under-served rural areas. The NRHM was initially tasked with addressing the health needs of 18 states that had been identified as having weak public health indicators.

In an effort to better this setup, the Government of India setup the NHSRC (National Health Systems Resource Centre), under the NRHM, to serve as an apex body for technical assistance. The goal of this institution is to improve health outcomes by facilitating governance reform, health systems innovations, and improved information sharing among all stakeholders — at the national, state, district and sub-district levels — through capacity development and convergence models.

One of the areas that the NHSRC works in is the provision of universal healthcare services. Universal access to good quality services — services that are effective, that are safe and satisfying to the patient; services that are patient and community centred, and services that make efficient use of the limited resources available.

The approach for achieving these objectives involves ensuring that every single health facility is scored against pre-defined standards with periodic supportive supervision for ensuring continual improvement.

There are three main components to conducting an assessment,

- Facilities
- Assessments themselves, and
- Facilitators

Facilitators conduct Assessments for Facilities.

Facilities are hospitals or other healthcare systems that exist at different levels,

  • National level
  • State level
  • District level
  • District Hospital level

Based on their level, facilities would be eligible for a particular type of assessment.

There are two main types of assessments in the system,

  • National Quality Assessment System (NQAS): Is a system which has incorporated best practices from the contemporary systems, and contextualised them for meeting the needs of Public Health System in the country
  • Kayakalp assessment: To complement the government’s ‘Swachh Bharat Abhiyan’ (cleanliness in public spaces campaign), the Ministry of Health & Family welfare, Government of India launched a National Initiative to present awards to public health facilities that demonstrate high levels of cleanliness, hygiene and infection control

Assessments are a set of pre-defined standards against which facilities are scored. Assessments happen periodically throughout the year under supervision to ensure continual improvement.

Facilitators are people with varied experience, who are picked based on the type of assessment. For instance, National level assessments would require facilitators with a certain set of requirements as compared to a State level assessments. For instance, national level facilitators will consist of representatives from the programme divisions (maternal health, child health, family planning, etc.) of the Ministry of Health and Family Welfare, Government of India and National Health Systems Resource Centre.

How does the assessment process work?

The assessment process requires Facilitators to give a Score (of 0, 1 or 2) to a Measurable Element (ME).

Each ME belongs to an Area of Concern (AoC) and an AoC belongs to a Standard.

Standards: These are broad thematic areas with respect to cleanliness & hygiene, and can be termed as the “pillars” of the system.

Area of Concern: Each theme (Standard), has a fixed number of criteria that cover specific attributes.

Measurable Element: Is the lowest and most tangible unit of an assessment. MEs are specific requirements that the facilitators are expected to look for in a facility for ascertaining the extent of compliance and award a score.

Checkpoints: In the NQAS type assessment, MEs are broken down further into Checkpoints. Checkpoints are departmental checklists.

This is how the above-mentioned elements exist in the Assessments,

Assessments for Facilities are done via Checklists, which encapsulate all of the above (Standards, AoCs, MEs and Checkpoints).

How were assessments conducted prior to the app?

Facilitators were handed sheets of paper with all the Standards, AoC and ME on them. Facilitators would traverse back and forth through this list, assign a compliance score to a ME until they were done with all AoC and subsequently with all Standards.

Advantages of the offline system,

  • Easy and fast scanning of Standards, AoCs and MEs
  • This medium requires little to no training

Disadvantages of the the offline system,

  • Hard to keep track of progress. Facilitators have to scan and do this themselves by repeatedly going through the list
  • Force facilitators to conduct their assessments by the list, rather than what is convenient
  • Unobliging towards writing comments for scores awarded to MEs
  • Can’t generate reports immediately
  • Submitting Assessments as a physical copy and manually syncing the results across the entire district/state/nation

What is Gunak?

Based on the disadvantages mentioned above, Nikhil (senior member of the NHSRC) thought it’d be best to use technology to make the process of conducting and syncing assessments easier. Gunak is the app that aimed at doing this.

Minimum feature list we aimed to launch the app with,

  • Conduct NQAS and Kayakalp assessments
  • Motivate facilitators to enter comments for the scores they give
  • Allow assessments to be conducted offline
  • Sync assessments once facilitators were in an area with active internet connection
  • View detailed reports across all Standards, AoCs and MEs for finished assessments
  • Sync reports of finished assessments for peers/superiors to view/review

The challenges we faced,

  • Maintain familiarity while transitioning facilitators from an offline to an online system
  • Translating a multi-tier architecture to mobile

Navigation

Usage: For an assessment to be complete, facilitators have to finish all MEs across all AoCs.

Usage Pattern: Facilitators, physically visit facilities to conduct assessments. The offline medium sometimes forced the facilitators to finish Measurable Elements in a sequential order (as displayed on paper) since it would be easier to keep track of the progress of the assessment.

Notes:

  1. MEs are specific department-wise questions for a facility. Since most facilities aren’t built the same way, following a sequential pattern wasn’t the way to go ahead.
  2. The assessments are usually carried out over a period of 3–5 days.

We wanted to design a system that would be flexible and not dictate facilitator behaviour. A system that would always keep the facilitator aware of where they are and their progress. In addition to this, we had to ensure that readability and usability were the main focus since facilitators moved around a lot while conducting assessments.

The bottom navigation for an ME, allows facilitators to know the progress of the AoC these MEs belong to. It works as a navigation system where facilitators can jump forward to answer an ME and come back to answer another ME.

Search

We wanted to find an equivalent for the ‘flip & find’ function, that facilitators perform on paper, for the app.

Search allows facilitators to find MEs, AoCs and Standards.

Our Search feature isn’t a simple text match. As seen below, it can identify that the word ‘hygiene’, could pertain to a Standard, an AoC or MEs.

Reports

One of the main drawbacks of the offline medium was its inability to generate reports. A facilitator or their superior would spend hours going through an assessment and assign a score for the same.

We took advantage of technology to provide detailed reports based on Departments, AoC and Score, which can be shared as an excel sheet or as an image.

Who did we work with?

This project would not have been possible if it wasn’t for the amazing team at Samanvay. This is our second project with them, you can read about the first one here,

Designing for Rural India — Part 1

App Launch and Reception

The Gunak app is being rolled out in phases. Its first launch was in August 2017 by the Ministry of Health and Family Welfare, the app has a 4.8* rating on the play store.

Thank you so much for reading this. If you found this interesting, don’t forget to 👏 👏

If you have questions or thoughts about the post and/or would like to reach out to us outside of Medium, send us an email, moshimoshi@nilenso.com

🙏


Gunak — Designing with the Indian Government was originally published in uxdesign.cc on Medium, where people are continuing the conversation by highlighting and responding to this story.

Original post by Varun Pai - check out Stories by Varun Pai on Medium

Designing for Rural India — Part 1

Designing for Rural India — Part 1

Journey of designing OpenCHS with Samanvay

India does not have a National health insurance or universal health care system for all its citizens. This has propelled the private sector to its dominant position in the healthcare market. Private companies provide the lion’s share of healthcare services in the country.

Despite the structures in place to ensure equality and funding from government and non-government sources, we still observe a visible gap in access to healthcare in rural areas compared to cities. A staggering 68% of the population lives in rural areas and has no or limited access to hospitals and clinics. Consequently, the rural population mostly relies on alternative medicine and government programmes.

If one had to paint a picture of rural India, it would be people living in mud houses in small villages. These villages have next to no electricity supply. There are setups of solar power stations which people use to charge their cellphones. Travelling to these villages is not always easy. One would require to change at least three different modes of transport to reach many of these villages. The residents seek out healthcare in cases of pregnancy and severe illness like Tuberculosis, Dengue, etc. However, villagers often do not seek treatment for early symptoms which appear less dangerous. This is not always due to lack of awareness. It is often also the case that infrastructure to support the long tail of healthcare is simply not that accessible in rural India.

Healthcare in Rural India

The public healthcare in rural areas has been developed as a three-tier structure based on predetermined population norms.

1. CHC (Community Health Centres)

Community Health Centres form the uppermost tier and are established and maintained by the State Government. Community health centres are staffed by four medical professionals supported by twenty-one paramedical and other staff. Surgeons, physicians, gynaecologists and paediatricians provide comprehensive care in each CHC.
Each CHC has thirty indoor beds, an Operating Theatre, X-ray, Labour Room, and Laboratory facilities. The community health centre provides expert facilities in obstetric and other care for patients referred to them by the four primary health centres within their jurisdiction.

2. PHC (Primary Health Centres)

Primary Health Centres (PHCs) comprise the second tier in rural healthcare. PHCs provide integrated, curative and preventive healthcare to the rural population with emphasis on preventive and promotive aspects. Activities include promotion of better health and hygiene practices, tetanus inoculation of pregnant women, intake of IFA tablets and institutional deliveries. A medical officer is in charge of the PHC supported by fourteen paramedical and other staff. Each primary health centre has four to six beds. Patients are referred to the PHCs by six sub-centres.

3. Sub-centres

A sub-centre is the most peripheral institution and the first contact point between the primary healthcare system and the community. An Auxiliary Nurse Midwife (ANM) is in charge of six sub-centres each of which provides basic drugs for minor ailments. A sub-centre provides services in relation to maternal and child health, family welfare, nutrition, immunisation, diarrhoea control, and control of communicable diseases. ANMs also use Anmol Tablet, a product that aids in maintaining and collecting data, specific to primary health.

4. Non-government Infrastructures

Apart from the government bodies there are other players in the system, which are closest to the villagers (bottom most in this tier). There are private hospitals, which run to provide special services or even basic healthcare.

Accessing health support is not that easy for village residents. They have to travel long distances to visit public hospitals spending money, and time that could be spent doing their daily chores. That’s when community health services come to play.

There are non-profit NGO Hospitals which run Community Health Services (CHS). They hire and train health workers who work closely with villagers in providing health services and education.

Health Workers who work as a part of the Community Health Services are known as VHWs (Village Health Workers), as a part of CRHP (Comprehensive Rural Health Programme). Jamkhed is a programme run under CRHP.

Jamkhed is centered around mobilising and building the capacity of the community, empowering the people to bring about their own improvements in health and poverty-alleviation. This is one of the better known and appreciated community health systems.

Health Workers with a monthly visit chart on the wall

Role of VHW ( Village Health Workers )

VHWs are individuals selected by the villagers. They are responsible for providing consultation and prescription on basic health care. Their appointment by the community helps establish villagers’ trust in them.

VHWs typically take care of a single village, but if required, they can be responsible for up to five villages. They are trained in basic healthcare, understanding symptoms and personality development. Since they are only trained in basic healthcare, they escalate severe cases and recommend the patients to visit hospitals. Quite often these volunteers are women.

Apart from this, VHWs also bust widely held superstitions by providing elementary health education.

Health workers use their considerable interpersonal communication skills to bring about important behavioural changes with respect to reproductive and hygiene practices in their rural communities.

How do they operate now?

The infrastructural support that these health workers get is mostly via Community Health programs and some inventory support from the government.

Inventory procurement list and inventory at the health centers

Here are some highlights about their daily operations -

Use of Paper:

The health workers still use paper for most of their work. They are provided with a chart that maps various symptoms to common ailments and relevant medication. While this may enable the health workers to swiftly treat common ailments, the strict mapping unfortunately severely restricts their ability to correctly identify edge cases or more subtle health issues.

Inventory List:

Procurement of medicines is also done using paper. Health workers also track the need for medicines, availability and expiry dates of the medicines. Medicines are procured from Sub-centres where the health workers visit often to give reports to ANM’s about their respective villages.

Patient History

The health workers aren’t equipped to look at patients history at the time of consultation. They keep manual records which are too comprehensive to look into at the time of visits.

Health Worker educating a resident about preventive measures

How does OpenCHS help?

OpenCHS strives to fill this gap and provide a decision support system that helps a health worker perform diagnoses. The system also provides the health workers with the steps for treatment.

What is OpenCHS?

OpenCHS is an Open Community Health Service platform that works in collaboration with NGO Hospitals. OpenCHS is a mobile app that is used by Village Health Workers (VHW) in the field or in their clinics when patients visit them.

OpenCHS helps VHWs to record patient data, perform diagnoses and manage programme statuses. The app also enables the health workers to consider individual patients’ medical histories during their diagnoses.

Our challenges while designing the product

  1. Physical Constraints: Data is not recorded as someone on a desk job would. Health workers not only collect data with the app but they also have to use health equipment to take measurements. This requires the health workers to keep switching their attention between the patient and the application.
  2. No Electricity and Network Connectivity: VHWs don’t have access to electricity. They use basic cellphones (not smartphones), which they charge using solar charging stations located at central areas of villages. There is also next to no network connectivity which makes it difficult for an application to work in the field.
  3. Localisation & Multi-lingual Support: The application is intended to be used throughout multiple states of India. Each state has their own language. Some villages within a state may even use multiple dialects. We focused on providing multi-lingual support and localisation, in particular with regard to specialised medical terminology and concepts.
  4. Ease of Use: VHWs live in remote villages of India, where there is very little or no access to technology. They are used to basic cellphones, i.e. no smartphones. We had to be cautious about not having a higher learning curve for the application for them, so they don’t face issues when they are in the field.

What did we do?

Considering the challenges and constraints that we were working with, this is how we approached the design of the application.

It works offline:

We were aware that the user is not going to be connected to a network 98% of the time, so we made the app work offline. We store all data locally on the device. The app only connects to a server when synchonising data. Typically health workers visit a sub-centre or another place with internet connectivity monthly. Recorded data is reported to the hospitals as part of the synchronisation.

Image 1 — sync status notification | Image 2 — sync finished 50%

Decision Support:

The application provides decision support based on the recorded data and suggests treatment. We built our algorithm in collaboration with medical practitioners and took into account common health procedures. The algorithm even helps the health worker identify emergencies and provide appropriate medical care. When a patient needs medical attention from a trained medical professional, the application suggests them to inform the patients of the details and visit a hospital.

Image 1 — Patient profile and history | Image 2 — Treatment result after consultation

Localisation and Multi-lingual Support:

The application will be implemented with multi-lingual support. For each implementation, there will be localisation for specialised medical terminology used by the residents of the villages. Currently, we have an implementation in Marathi, which can be downloaded from here.

Ease of Use:

Ease of use was our major focus while designing this application.

  • Keep it simple, focused: We tried to understand different activities that a Health Worker performs, and based on those use cases, created focus in the application, instead of going by one interface for all flows, like a dashboard.
  • Attention on Iconography: We experimented with iconography using various styles and even with contextual icons. This quickly proved infeasible given that our users were stretched through rural India.
    We followed these simple rules of iconography:
    - Keep it simple and schematic, i.e. avoid details
    - 5 second rule, if you can’t think of that icon in five seconds then that icon probably is not a good choice
    - Memorability, making the icons distinct enough that they are remembered even after prolonged usage.
Few options of icons we considered for patient profile ; we finally picked the last one
  • Understand Behaviour: We tested an alpha version of the application with Health Workers to see if they are comfortable with data entry and understand input fields as concepts. To our surprise, the first thing the health worker did was swipe on the screen. It was most interesting because we knew that our users don’t use smart phones, so how did this come up as a first interaction in this person’s head? Perhaps media has been reaching them through means which one can’t imagine.
Testing of the alpha version with the health worker

So, What’s next?

The application is yet to be released. The plan is to implement it at one village first and then scale accordingly.
We are looking forward to two types of feedback. After the implementation of the application, the health workers will be trained. At this stage will be able to get quick feedback about usability and other challenges.

The second feedback will have a rather longer loop, where the health workers will be using it in the field and on their return we will learn about how it went and get more qualitative feedback. Here is all the documentation, including designs of the project so far.

Want to know more?

There has been much discussion about each flow and decision, in multiple small and large sessions that we will be sharing in detail shortly so that you can better understand our efforts. Keep on the lookout :)

Thanks to nilenso and Samanvay team for the opportunity to work on this interesting problem. I also appreciate the feedback from Kenneth & Trouble in better articulating this post.
Do get in touch with me (noopur@nilenso.com) for any further questions or details. Any feedback will be highly appreciated.

Noopur wrote this story to share knowledge and to help nurture the design community. All articles published on uxdesign.cc follow that same philosophy.


Designing for Rural India — Part 1 was originally published in UX Collective on Medium, where people are continuing the conversation by highlighting and responding to this story.

Original post by Noopur Varma - check out Stories by Noopur Varma on Medium