Typing Headers in ReScript


#1

I’m trying to type headers in ReScript, but … well, they’re dynamic. I checked out a few Ajax Reason projects, and it appears something along the lines of headers: Js.Dict.t<string> should work, or even headers: Js.Dict.t<(string, string)>. However, the compiler says they don’t match, and just says the header type doesn’t match. And by “header type” I mean, it prints out the entire object… so I don’t really have a clue on where to start trying to make it match.

{
    'access-control-allow-origin': '*',
    'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE',
    'access-control-request-headers': 'content-type,x-idempotency-key',
    'access-control-allow-headers': 'content-type,x-idempotency-key'
}

Any pointers? This is for both request and response type things.


#2

First off: please note that rescript has it’s own forum: https://forum.rescript-lang.org
Since you already use rescript syntax, your question would be better placed there.

What are you actually trying to do?
Do you need to send some specific headers?
If you have a type of JS.Dict.t<string>, this means you have a js object with all props being strings.

If you want to create a js object in the shape of

var x = {
  prop1: "some",
  prop2: "thing"
}

Then you would do something like this, if you want to use a Dict:

let x = Js.Dict.empty();
Js.Dict.set(x, "prop1", "some");
Js.Dict.set(x, "prop2", "thing")

The approach to use really depends on your usecase!
You could also use records or Js.t’s…


#3

Apologies, I mis-read some docs, I thought ReScript was a combination & replacement of Reason & Bucklescript. If I’m just writing simple Node apps, should I be using Reason or ReScript?

I’m trying to model headers coming in and going out, but they’re dynamic, so I assumed Dict was a good model since they’re always string / string name value pairs. I don’t care about specifics, just as long as headers is a Js.Dict.t, we’re good.


#4

The ReScript home page words it a little confusingly, but ReScript is separate from Reason. For historical reasons, ReScript does support Reason syntax. If writing Node apps, you are using ReScript. The syntax you’re using depends on the file extension:

  • .re/.rei: Reason
  • .res/.resi: ReScript
  • .ml/.mli: OCaml

Anyway, to type headers it’s actually better to use array<(string, string)>, because requests and responses may have headers with duplicated names. It’s a common problem in many libraries/programming languages when people use maps and lose some headers like Set-Cookie because maps discard duplicate keys.