My First Suave Api(tm)

      2 Comments on My First Suave Api(tm)

Subtitle: You Know Nothing Eelco Mulder

With my previous blogs I’ve been setting up everything around developing with F#, but now it’s really time for me to just start coding. I’ve read a lot about F#, but when I start to code myself… I seem to know very little! So from now I’m just gonna get my hands dirty and just learn by coding, meanwhile blogging about it so I hope it’ll stick better.

So I started with this little simple Crud web api (source here: https://github.com/EelcoMulder/SuaveCrud), build using F# on .Net Core, Suave and a SQL Server Express database. To connect to the database I used the SQLProvider, I found it easy to use and it has the linq syntax to query the database; automatic win for me.

I see other F# developers put their code in a few files, sometimes just one, but because I’m a C# developer and not some SAVAGE I got the urge to bundle certain code in separate files šŸ˜‰

In the file Types.fs I created a little type Serie. In Database.fs I create the connection to the database using the SqlProvider. At first, when I ran dotnet build, I got the following error:

The type ‘String’ is required here and is unavailable. You must add a reference to assembly ‘System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e’

This is because the SqlProvider is a Type Provider and those are not supported by .Net Core out-of-the-box. To fix this, add the FscToolPath and FscToolExe to your fsproj:

    C:\Program Files (x86)\Microsoft SDKs\F#\4.1\Framework\v4.0
    fsc.exe

In Serie.fs I created a module for database specific actions, you might call this a repository. I Had a little light bulb moment when I found out how to pass the datacontext. Use the type provider young Skywalker! When I implemented the add function and tested it by posting data it gave me this error:

System.NotSupportedException: Enlisting in Ambient transactions is not supported.

I found a solution on the GitHub of the SqlProvider here, so I could solve it quickly by changing to call the GetDataContext function.

    let getContext = 
        SeriesSqlProvider.GetDataContext( { Timeout = System.TimeSpan.MaxValue; IsolationLevel = IsolationLevel.DontCreateTransaction})

Then Api.fs, I use this to convert to or from Json and wrap http response around the calls to the repository. I made it generic what was a bit out of scope of this blog, but it was a good exercise.

Again check the GitHub for the code, I know it needs a lot of work but I’m happy I’m getting some where. Mostly it is fun! Always open to suggestions on how to solve things better or differently!

2 thoughts on “My First Suave Api(tm)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.