JavaScript Sending me stupid stuff, like... Object

I don’t get how to get Objects from JavaScript. I’ve been successful at binding to JS functions, and even parsing strong types via JSON binding… but… I’m creating a library. The user can pass a “list of headers”. That’ll most likely be an Object like this:

{
  "content-type": "application/json",
  "authentication": "Bearer cowtokenmoo"
}

Now, I can’t like do an Object.entries/values in ReScript, so… I kind of gave up and just wrote a JavaScript function to run Object.entries for me, so when ReScript gets it, I can just go Js.Dict.fromArray… but now I’m stuck on what’s the parameter type. Like… I tried Js.Obj.t, but that doesn’t work.

const headersToEntries = headers => {
    if(headers) {
        return Object.entries(headers)
    }
    return []
}

module.exports = {
    headersToEntries
}
@module("./headersToEntries") external headersToEntries: Js.t => Js.Array.t<Js.Array.t<string>> = "headersToEntries"

Should I just give up, wrap my ReScript library in JavaScript, and run an Object.entries on the headers Object before it hits ReScript, OR should I yell at my users to do it themselves, OR do y’all have other ideas?

If your headers object has sting values only then it’s already Js.Dict.t<string> on rescript side
See here

DUDE!

node sandbox.js 
[
  [ 'content-type', 'application/json' ],
  [ 'Authorization', 'Bearer cow' ]
]

:smile::metal:t3:Thanks a ton, that worked!

1 Like

Just fyi, using an object to model headers is usually incorrect, because object keys must be unique, but header names are not required to be unique. E.g., Cookie, Set-Cookie. Putting multiple of these in an object is undefined behaviour but most like will drop all but one.

->  node
Welcome to Node.js v12.13.0.
Type ".help" for more information.
> const headers = {
... 'Set-Cookie': 'a',
... 'Set-Cookie': 'b'
... }
undefined
> headers
{ 'Set-Cookie': 'b' }
6 Likes