Based on this points, we can see that we are facing two side effects: latency and exception.
Latency is handled by transforming a function to an asynchronous function which returns an Async<'a> result. Exception will be handled by a special type that we will define and call ApiResult<'a>. It will either be a Success or a Failure.
By making side effects explicit, we end up with the following function definition:

So what can we do with Async<ApiResult<'a>> type? A lot! Thanks to computation expression in F#, we can manipulate the underlying type DataType directly without thinking of Async orApiResult! In other words, we can write code without worrying about latency and exception. Doing this will allow us to write the code we saw in (1).

Making the computation expression

Just like the async computation expression with async {...} workflow, we want to define our own apiCall computation expression which will allow us to use apiCall {...} notation to write workflows which handle asynchronous calls and exceptions.
But where do we start? Here’s what we need to do:

Define ApiResult

Make our ApiCallBuilder which is a type that allows us to instantiate the computation expression (’…Builder’ is just a convention, you could have it called ‘Hello’ and it would have worked the same way)

Instantiate the builder apiCall and use it!

So let’s start by defining what is an ApiResult.

Defining ApiResult

ApiResult will capture every possible outcomes of our Api calls and Json deserialization. Like what we saw earlier, the api may throw an error or the json may throw an error. So we define it like follows:

This type specifies that ApiResult is either a Success or Failure where the Failure can be any of the followings: Unauthorized, NotFound, UnsupportedMediaType, BadRequest, JsonDeserializeError.

Defining ApiCallBuilder

To build a computation expression, two methods are required Bind and Return (there are a bunch of them, you can go ahead and implement all if you want. It will give you more power in the workflow which is within the curly braceshttps://msdn.microsoft.com/en-us/library/dd233182.aspx). So we define it like that:

let! unwrapps the special type. In let! xApiRes = m, m is of type Async<ApiResult<'a>> and xApiRes is of type ApiResult<'a>. See what we did there? let! successfully transformed Async<ApiResult<'a>>' to ApiResult<'a>, it took away Async!

return and return! let you exit the workflow and return a result. The difference is that return lets you pass a underlying type 'a' and exits with a wrapped type Async<'a>' whereas return! lets you directly pass wrapped type Async<'a'> and exits with the same wrapped type Async<'a'>.

To define the builder we used retn and bind.

retn takes a normal input of 'a and tranforms it to a special type of Async<ApiResult<'a>>.

bind is used to transform a function that takes a normal input and returns a special type'a -> Async<ApiResult<'b>> to a function that takes a special type and return a special typeAsync<ApiResult<'a>> -> Async<ApiResult<'b>>.

Alright, we’ve done great so far. We are done with the ApiCallBuilder. We can now instantiate it and use it as a keyword!

Amazing! We are now manipulating simple types: string and our ownDataType instead of Async<ApiResult<string>> and Async<ApiResult<DataType>>. This is what we wanted to achieve at the beginning. Isn’t it wonderful? We used the computation expression to take-out latency and exception but you can now go ahead and create your own computation expressions which fit your scenarios to abstract side-effects like logging or persistence or anything else you like.

Where’s the WebSharper

At the start I said I will make a Ajax call from a SPA with WebSharper so let’s do it.

This method creates the AjaxSettings which contains all the information about the http request and post it using JQuery.Ajax(settings). Async.FromContinuations is used to turn a method which use Success and Error callbacks to a function which returns an Async result.

We also define utility methods to convert http code to Failure and to deserialize Json string to ApiResult.

We use the type AuthToken to represent the token. It allows us to type the argument of methods expecting a string token and take an AuthToken instead. Credentials is a record type which holds the user name and password.

Great now that we have our foundation for Ajax calls, let’s make the first method getToken.

The Ajax call returns a Async<string> but it can throw exception so we want to make the exception explicit in the type. In order to do that, we try catch the Ajax call and return a Async<ApiResult<string>> which will take in account the exception. If you remember, an ApiResult is either a Success or a Failure and in the case of a Failure, it can be Unauthorized or NotFound etc…
After that we pipe it to the deserialization with tryDeserialize which in case of error, returns a Failure of JsonDeserializeError.
We do the same for getData.

In getData we see how to use our apiCall keyword to write nice code to get the token and then use it to get the data.
And we are done! What we have built is a complete recipe to interact with our REST Api from WebSharper front-end. The code looks simple now (I think…) but it handles asynchronous calls and handles exception in the background!
If we need to make other calls to the Api, we can just write it inside an apiCall {...} block and we get async and error handling for free!

Conclusion

Today we explored how to create a computation expression in F# and how we could use it to write simple code which would abstract latency and exception. We also learnt how to query a REST Api from a WebSharper SPA using WebSharper.JQuery and how to deserialize the result using WebSharper.Json. I hope you enjoyed this post as much as I enjoyed writting it. I am by no mean an expert, in fact I just started to learn about F# two months ago and WebSharper a month ago and I love it! So if you find any errors or if you feel that this is not the right way, please share with me your remarks. Thanks for reading!

Comments

Post a Comment

Popular posts from this blog

Absolute layout and relative layout Xamarin formsIn Xamarin Forms, layouts are used to position elements in the page.
There are multiple layouts available like stack layout, grid layout, table layout, absolute layout and relative layout.
Stack layout is straight to grasp the concept, we stack elements one by one horizontally or vertically.
Grid layout is also straight forward, we define rows and columns and we place the elements by indicating the row index and column index.
On the other hand, absolute layout and relative layout isn’t that straight forward because in Xamarin it is NOT the same as positions in CSS.So today, we will see how and when we can use absolute layout and/or relative layout in our advantage.
This post is composed by two parts: 1. Absolute layout
2. Relative layout
1. Absolute layoutThe first thing to understand is that absolute layout has nothing to do with CSS absolute position.
In Xamarin Forms. absolute layout allows us to position elements in the page by pre…

Build an accordion view in Xamarin.FormsFew weeks ago I posted about absolute and relative layouts.
Layouts are called Layouts because they contain children which are placed in a particular way.
Xamarin.Forms has a lot of layouts and views to structure pages like grid, table view or list view.Today I would like to show you how we can use some of these basic views to build an Accordion view.Here’s a preview of the Accordion view:Full source code available on GitHub - https://github.com/Kimserey/AccordionView/blob/master/Accordion/AccordionView.csThis post will be composed of four steps:Create a BindablePropertyDefine the accordion expandable sectionDefine the accordion viewUsage sample1. Create a BindablePropertyAs we saw in one of my previous post,
Xamarin.Forms works around data bindings.
View properties are bound to viewmodel properties.Default views like Label, Button, ListView or TableView come with the necessary bindable properties like BackgroundColor, TextColor, ItemsSource, It…

Use Font Awesome from your Xamarin.Forms projectIcons are important in mobile applications where space is limited.
We use icon everywhere to convey action intent like + would be to add an item or a bin would be to delete one.
There are two ways to add icons to our mobile app:with imageswith fontsToday we will see the second option - how we can add Font awesome to our Xamarin.Android project and how we can use it from Xamarin.Forms.
This post will be composed by three parts: 1. Why Font Awesome
2. Add Font Awesome to the Droid project
3. Use with Xamarin.Forms
1. Why Font AwesomeIf you are familiar with Web development, you must have encountered Font awesome http://fontawesome.io/.
It is an icon font containing lots of icon for every type of usage.
The advantaged of using a font is that we can leverage the text options, like text color or text size, to easily update the style of the icon to match our app.Let’s see how we can bring Font Awesome to the Droid project.2. Add Font awesome…