2

I would like to send constructors via EJSON through methods:

server.js

Meteor.methods({
  'testConstructor' (doc) {
    console.log(doc) // {}
  }
})

client.js

Meteor.call({ type: String })

I thought of adding the types via EJSON.addType but it currently only supports instances and not constructors. I tried to wrap the String constructor inside a class like this:

Meteor.startup(function () {
  class StrWrap {
    constructor (val) {
      this.val = val
    }

    toJSONValue () {
      return {
        value: this.val
      }
    }

    typeName () {
      return String.name
    }
  }

  EJSON.addType(String, function (json) {
    return String
  })

  const str = EJSON.stringify({ type: String})
  console.log(str) // {}
})

Still no chance. In a related issue it has been mentioned, that the EJSON supports String, Number etc. but I think that was targeting the instances of these classes.

I currently work this around using native JSON replacer for JSON.stringify and resolver for JSON.parse but this adds a full conversion layer to every DDP protocol interaction and I'd like to support constructors out of the box, so I can send schemas around for service discovery.

Jankapunkt
  • 8,128
  • 4
  • 30
  • 59
  • 2
    Interesting question, but yeah, I don't think that's possible. Constructors like `String` are functions, so you would need to add a type for functions to EJSON. I've tried `EJSON.addType('Function`, ..` after monkey-patching a `typeName` and `toJSONValue` into it to no avail. I also tried `String.__proto__.typeName = () => 'StringFn'` plus a `toJSONValue` patch and then `EJSON.addType('StringFn', ..)` which didn't work either. I was somewhat surprised by that, since you'd think that EJSON just calls `typeName` on the thing to stringify. – Christian Fritz May 07 '20 at 15:07
  • 1
    I found in the source that function typed values are skipped when it comes to converting the object for DDP message format, even if they would be defined as custom type. – Jankapunkt May 15 '20 at 13:27

0 Answers0