paint-brush
Modelling a Chat API using TypeScriptby@MuigaiMwaura
275 reads

Modelling a Chat API using TypeScript

by Muigai MwauraJuly 18th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Clear, clean and concise, are some of the adjectives I would associate with an API that makes for a pleasant and productive <a href="https://hackernoon.com/tagged/development" target="_blank">development</a> experience.

Company Mentioned

Mention Thumbnail
featured image - Modelling a Chat API using TypeScript
Muigai Mwaura HackerNoon profile picture

“Hands create art on a pottery wheel” by SwapnIl Dwivedi on Unsplash

Clear, clean and concise, are some of the adjectives I would associate with an API that makes for a pleasant and productive development experience.

TypeScript offers a great feature — discriminated unions — that you can use to build such API’s.

Discriminated unions, also called tagged unions, represent a finite, well-defined set of choices.

source

Implementing a discriminated union in TypesScript

If you have a class with a literal member then you can use that property to discriminate between union members.

As an example consider the union of a Square and Rectangle, here we have a member kind that exists on both union members and is of a particular literal type:

source

Designing the API

The Chat API will receive requests from chat users and return appropriate responses.

The chat users will issue the following requests:

  • Logon
  • Logoff
  • SendMessage
  • RequestNotification (request for notification of events in the chat room)

The server in turn will respond with one of the following notifications:

  • LoggedOnUsers (a list of users who available for chat, provided at logon time)
  • UserJoined (notification that a new user has joined the chat)
  • UserLeft (notification that a user has left the chat)
  • MessageFrom
  • Nothing (when the user log’s off there is nothing more to say)

The definition of the request model in TypeScript is as follows

… and likewise for the response

Thus, in a few lines of code I have described all the cases that the Chat API needs to handle.

I can then use a switch statement to handle every case as required.

The default clause in the switch ensures that we have handled all possible request types.

If I extend the API in future the compiler will ensure that I’ve handled the new cases. This is a fantastic way to future proof against bugs.

Thanks for reading and if you found this article helpful, please hit the 👏 button and share the article, so that others can find it easily. Cheers.