Skip to content

How to make an idiomatic Javascript library with Scala.js

Last updated on 22.11.2020

UPDATE: Article was updated to Scala.js version 0.6.7, which vastly simplifies Promises related section.

Scala.js opens a big world of frontend development to Scala fans. Most of the time Scala.js project ends up being an independent browser or Node.js application. But there are cases, where you would want to make a library for general frontend developers.

There’re some interesting gotchas in writing Scala.js library such way, that it will be natural to use for an average JS developer. In this article we will develop a simple Scala.js library (code) to work with Github API and will focus on the idiomaticity of it’s JS API.

But first, I’m sure you want to ask

Why would I do that?

Reasonable one.
You should consider developing such a library if:

  1. A client application for your Scala API backend already exists, and it’s native Javascript.

    Sad, you will hardly have a chance to write it from scratch with Scala.js, but at least it makes sense to write a communication / interpretation library for those guys.
    It will simplify interaction between you and frontenders in two ways:

    • You can hide some tricky client-side logic there, and expose much simpler API.
    • Your library can work on model classes, defined in backend project (see Cross-Building). You get typesafe isomorphic code almost for free and can forget about client-server protocol synchronization problems.
  2. You develop a public API for developers, like Facebook’s Parse.

    A perfect solution for a Javascript API SDK. See all the advantages of the previous case.

Recently, I’ve faced the first case. Moreover, our REST-like JSON API has two different browser based clients. So developing an isomorphic library was a logical choice.

Let’s start with our library.

Requirements

  1. As Scala developers we want to write all business logic in familiar functional style, being able to use all the handy Scala features.
  2. Library API must be natural for JS developers.

Setting up project

Such a project doesn’t differ from a regular Scala.js app. If you are new to Scala.js, you can read this tutorial first.

Folder structure:

resources/index-fastopt.html — a page that will just load our library and  resources/demo.js file, that will test the API.

API

The purpose of the library is to simplify Github API interaction. For simplicity, we’ll implement only one feature – loading users and their repos by login.

So it’s, basically, a public method and a pair of model classes, that store results (value objects). Model is the place we’ll start writing code.

Model

Let’s define model classes like this:

Everything is easy: User has some repos, a repo is either an origin or a fork. Good old Scala model. How do we export that to JS developers?

For a full reference of exporting features see Export Scala.js APIs to Javascript

Object creation API

Let’s look at, how we should expose such API. It seems an easy solution to expose the constructor:

But this won’t work. You don’t have Option constructor exported, so there’s no way to create homepage  parameter.

Moreover, there are additional limitation for case classes: You can’t export two case constructors that are under inheritance relationship. This code won’t even compile:

So what is the best choice? I found that it’s best to leave constructors alone and just expose JS-friendly factory methods, like this:

Here with the help of js.UndefOr we handle optional parameter JS way: you can pass a String , or don’t pass anything:

Note on caching Scala objects

Making client call  Github() every time is not the best API option. If you don’t need laziness, you can cache it upon startup:

Reading model properties

Seamless types

If we now try to read fork’s name, we’ll get undefined . Fair enough, it’s not exported. Let’s export model properties.

There’re no problem with native types like String , Boolean and Int . They can be exported as is:

A case class field can be exported with @(JSExport@field) annotation. An example for  forks property, that’s not a member of Repo trait:

Option

But as you already can expect, there’s a problem with
homepage: Option[String] . Well, we can export it, but this would be useless – to get the actual string value JS developer would have to call something on an option, and nothing is exported.

On the other side, we’d like to keep Option in place, so that our Scala code, that manipulates value classes, remains powerful and simple.  js.UndefOr[T] API is way less expressive.

A solution here is to export a special JS-friendly getter method:

Let’s try it out, it works:

We retained our beloved Option monad, and exported nice and clean JS API. Great!

List

User.repos is a List , and has the same problems with being exported. Solution here is the same too: we’ll just export it as a plain JS Array :

Now we can even map them 🙂 :

Sum types

There’s still one problem with  Repo trait. As we’re not exporting constructors, given a  Repo instance, JS developer can’t figure out, what kind of  Repo it is.

In Javascript there’s no pattern matching and using inheritance is not so popular, sometimes even questionable. So we have several options here.

  1. Depending on the context, provide methods like isFork: Boolean or  hasForks: Boolean at the base level. This is perfectly fine, but not general enough.
  2. Add  type: String (or whatever name feels suitable to you) property to all sum types.

I choose the second one, because it can be abstracted and used throughout the whole codebase. Here’s how it can be done. Let’s declare a mixin that exports a type property:

We have to use a different name for scala definition, because it’s a reserved word.
That’s it! We can now mix it in:

… and use it:

To make this a little safer, we can store type names constants, that can be compared with instance type property. This can be done typesafe:

Having this helper class we can define these constants in our Github global for example:

Now we can avoid strings in Javascript! An example:

That’s how we dealt with sum types.

What if I can’t change object, that I want to export?

This is a case if you want to (maybe, partially) export your cross-built model classes or other imported library objects. The solution is the same to Option and List with the only difference: you have to implement JS-friendly replacement classes and conversion yourself.

An important rule here is to use JS replacements only for export ( Scala => JS) and instance creation ( JS => Scala ). All business logic must be implemented with pure Scala classes.

Let’s say you have a Commit class, that you can’t change:

Here what you can do to export it:

Then, for example, a Branch  class, that you own, would look like this:

Since in JS environment commits are represented with CommitJS objects, a factory method for Branch  would be:

Of-course, this workaround is not a beautiful thing, but at least it’s type checked. That’s why I think it’s preferable to view your library not only as a value-classes proxy, but as a facade that hides redundant details and simplifies the API. That way you won’t even need to export the underlying model.

That’s all for exporting model. Let’s move on to the more interesting part – loading the content from Github API.

AJAX

Implementation

For the brevity purposes we will use scalajs-dom Ajax extension as a “network” layer. Let’s for some time forget about how we’re going to export things, let’s just implement the API.

For the simplicity, we’ll put everything AJAX-related into API object. It will have two public methods: for loading user and loading repos.

We will also implement a DTO layer, to decouple API from the model. For type-safe error handling we’ll use Xor type from Cats library. The result type of the method call will be Future[String Xor DTO], where DTO is the type of requested data and String will represent error.

I’ve mentioned everything for this listing to be more understandable, here it is:

Deserialization code is hidden, it’s not interesting. The load method returns string error, if response code is not 200, otherwise it converts the response data to JSON and then to DTO’s.

Now we can convert our API results into model classes.

Here we use a monad transformer to combine these “disjunctioned” futures, and then convert DTO’s into model classes.

Well, that is quite idiomatic functional Scala, lots of pleasure. Now let’s think about how we will export  loadUser method to library users.

Share the Future

To follow the article goals we need to answer the question: what is the idiomatic way to handle asynchronous call in Javascript? I already hear experienced frontenders laughing, because there are no such thing. Callbacks, event emitters, promises, fibers, generators, async/await — all of them are somehow valid approaches. So what should we choose?

I think, the closest thing to Scala Future in Javascript are Promises. Promises are very popular and are already native in most modern browsers. So we’ll stick with them.

First, we must let our Scala code know about those promises. Until Scalajs 0.6.7 we would have to use Promise typed facade from scalajs-dom. But with Scalajs 0.6.7 things became much easier, we will just use the “standard” Promises.

All we have to do now is to convert a Future into Promise. Again, since version 0.6.7 this is not more a problem — there’s a toJSPromise converter in JSConverters . We will just need to help it with the left side of our Xor — convert it to a failed Future to get a rejected Promise:

So let’s share the promise with our JS friends! As usual, we put it to Github object, near the original method:

Here in case of failed future we’re rejecting promise with the exception message. That’s all, we can test the whole API now:

Well, we did it! We can use Futures and everything else we are got used to — and still export idiomatic JS API.

For more API usage examples see full demo.js. To play more with the project, just fetch the repo, then build and run it.

Conclusion

Putting it all together, here are some general advice on writing a Javascript library with Scala.js:

  • Cache exported objects on startup.
  • Export seamless types “as is”.
  • Don’t export Options, Lists and other Scala standard. Put a JS-friendly getter nearby, that converts to  js.UndefOr and js.Array. BTW, same with  Map => js.Dictionary.
  • Don’t export constructors. Use a JS-friendly factory method. JS-friendly means it accepts js.* types and converts it to Scala standard types.
  • Mixin a string type property into sum types.
  • Export Future s as js.Promise s
  • Scala first. You are a Scala developer, so don’t limit yourself in any way: use all the power you like. You know now, that you’ll be able to export it.

Links

Published inSoftware Development

3 Comments

  1. oleg oleg

    Scala GWT? не?

    • Не:) Немного устаревший ответ, но хороший:
      http://stackoverflow.com/questions/18557181/scala-js-vs-scala-gwt-for-client-web-development?answertab=votes#tab-top

      Если вкратце, GWT – это огромный фреймворк, а scala.js – просто способ писать под браузер на Scala. Например, ты можешь подключить scalajs-react и написать проект на Scala, а на выходе у тебя будет приложение на обычном ReactJS.
      Чтобы лучше понять, надо потыкать 🙂

      • oleg oleg

        Ну ок 🙂

Comments are closed.