Echo JS 0.11.0

<~>
gcanti 3726 days ago. link 1 point
Hello,
this is a divulgative article, but I think that type combinators can be very useful also in practice:
I'm thinking of using them as a JavaScript internal DSL to describe, with a compact notation, the structure of a JSON.
Say you have this JSON (excerpt from the GitHub JSON API `https://api.github.com/repos/facebook/react`):

    {
      "login": "facebook",
      "id": 69631,
      "avatar_url": "https://avatars.githubusercontent.com/u/69631?v=2",
      "gravatar_id": "",
      "url": "https://api.github.com/users/facebook",
      "html_url": "https://github.com/facebook",
      "followers_url": "https://api.github.com/users/facebook/followers",
      "following_url": "https://api.github.com/users/facebook/following{/other_user}",
      "gists_url": "https://api.github.com/users/facebook/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/facebook/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/facebook/subscriptions",
      "organizations_url": "https://api.github.com/users/facebook/orgs",
      "repos_url": "https://api.github.com/users/facebook/repos",
      "events_url": "https://api.github.com/users/facebook/events{/privacy}",
      "received_events_url": "https://api.github.com/users/facebook/received_events",
      "type": "Organization",
      "site_admin": false
    }

You can describe succinctly the structure of the API payload with a struct combinator

    var Payload = struct({
      avatar_url: Str
      events_url: Str
      followers_url: Str
      following_url: Str
      gists_url: Str
      gravatar_id: Str
      html_url: Str
      id: Num
      login: Str
      organizations_url: Str
      received_events_url: Str
      repos_url: Str
      site_admin: Bool
      starred_url: Str
      subscriptions_url: Str
      type: Str
      url: Str
    });

Now this is a simple example (no nested structures) but when the payload is more complex, the notation become even more useful

Replies