How to bind to a function inside an object inside a module?

I am trying to bind to a function like this:

const connect = require("mongodb").MongoClient.connect;

So far I haven’t had success using @bs.module.

Here’s what I have come up with so far using %raw:

module MongoClient = {
  type t

let connect: (
  . string,
  (Js.Nullable.t<Js.Exn.t>, Js.Nullable.t<MongoClient.t>) => unit,
) => unit = %raw("require(\"mongodb\").MongoClient.connect")

I was wondering if there was a nicer way to achieve this binding?


Hey :slightly_smiling_face:

I don’t know, if the types are correct, because I am not really familiar with mongodb, but this should bring you a step closer:

To explain whats going on there:
First we are importing the default exported mongodb with @bs.module("mongodb") and tell rescript, that there is a value with the name MongoClient which it should get (@bs.val).

After that, we are defining the connect method and tell rescript, that this is a method, which should be called on the type t (which we defined as MongoClient above).

I hope this explains it a little bit :smile:


Use @bs.scope:

module MongoClient = {
  type t
  type connectCB = (. Js.Nullable.t<Js.Exn.t>, Js.Nullable.t<t>) => unit

  @bs.module("mongodb") @bs.scope("MongoClient")
  external connect: (string, connectCB) => unit = "connect"

let () = MongoClient.connect("", (. _err, _client) => ())

@eWert-Online thanks for the explanation, was very helpful.

@yawaramin great simple solution, thank you.