DEV Community

Prateek
Prateek

Posted on

Date Interface for Frontend

Hello fellas,

The aim of the writeup here is to validate the thought process behind creating a custom date interface to be used across multiple frontnend projects.

What does an application of date library on frontend looks like ?

An example of a date utility on frontend would be, say
My API gives me date as a string in DD/MM/YYYYin response and I want to use it for validating a Create operation.

if (date < date.now() + 180 days) 
 allow create
else
 don't
Enter fullscreen mode Exit fullscreen mode

How do I achieve this ?

I would convert the date string into a date object. Once I have the date object, I can add 180 days to it and comapre this new date object with the current date.

Like this we have numerous applications of Date on frontend

What is date interface and why it makes sense ?

Date Interface is the face of Date library for all my consumer applications. The consumer (the project) say wants to convert date string into a Date object ? Now the developer, does not need to think what should be the type of date object or which date library I should use, etc etc.

Instead the Date Interface exposes the below funtion

let make: (~date: string, ~format: string) => Date.t
Enter fullscreen mode Exit fullscreen mode

It takes a date string and a valid date format (we can further optimize the format argument to accept only valid formats) and returns a type Date.t Now the developer can use this type to interact with other functions exposed by this date interface, like a toString function to convert date object to a specific format for display.

let toString: (~date: Date.t, ~format: string) => string

Enter fullscreen mode Exit fullscreen mode

Am I rewriting a date library here ?

The answer is, I am rewiting only the interface. Underlying the interface I would be using a library like Moment or DateFns to perform my operations.

Why?

The consumer will be unware of the implementation details.
They don;t need to worry about the Date library being used and skim through the documentatiin

I can easily plug and play libraries without affecting my end consumer. Every function in my interface is a pure function, with defined input and outputs. My custom type Date.t helps me achieve this. Until that contract holds, I can try out a lot of stuff inside. Sounds cool :), right?

Under the hood we may take best of both worlds, and use two different date libraries to achive two different things. Not
a very ideal scenario but yes. Quite helpful when you are migrating libraires. Some functions are on old libraries and the other are on the new one.

Top comments (0)