threads.js icon indicating copy to clipboard operation
threads.js copied to clipboard

[QUESTION]: Custom message serializers

Open simplecommerce opened this issue 4 years ago • 2 comments
trafficstars

Hi,

I was reading the topic about Custom message serializers.

And I had a question.

If I am passing an object with the following structure.

{
   id: "string",
   getFunction: function() {
     return "something"
   }
}

I am not sure that I understand how I would use that feature in order to make sure that in the Worker I am able to call the getFunction method.

Is there a working example somewhere I can read upon with a scenario similar to this?

Thanks!

simplecommerce avatar Apr 28 '21 17:04 simplecommerce

Hey @simplecommerce. Guess we need to improve on the docs here…

Regarding your example: So the issue is that you cannot pass that object between threads, since functions cannot be serialized.

So instead of trying to pass the object as is, you can register custom serializers to transform this object into something else before passing it between threads and then deserializing it back into its original form afterwards.

In your concrete example you might want to do something like this (find the documentation here: https://threads.js.org/usage-advanced#custom-message-serializers):

const MySerializer = {
  deserialize(message, defaultHandler) {
    if (message && message.__type === "sample-object") {
      return {
        id: message.id,
        getFunction() {
          return message.value
        }
      }
    } else {
      return defaultHandler(message)
    }
  },
  serialize(thing, defaultHandler) {
    if (thing && typeof thing.id === "string" && typeof thing.getFunction === "function") {
      return {
        __type: "sample-object",
        id: thing.id,
        value: thing.getFunction()
      }
    } else {
      return defaultHandler(thing)
    }
  }
}

registerSerializer(MySerializer)

Tell me if that makes it clearer! Maybe you can make some suggestions how to improve the docs 🙂

andywer avatar Apr 29 '21 20:04 andywer

@andywer Thanks for your example, I will do some tests using it as a sample and see if I am able to make it work. Thanks again!!

simplecommerce avatar Apr 30 '21 08:04 simplecommerce