Aaronius / penpal

A promise-based library for securely communicating with iframes via postMessage.
MIT License
389 stars 56 forks source link

Feature suggestion: allow nested `methods` object #12

Closed jrencz closed 6 years ago

jrencz commented 6 years ago

I thought it may be useful to be able to pass nested object (tree of any depth with functions as leafs) as methods:

Penpal.connectToParent({
    methods: {
      method1(),
      foo: {
        foo1(),
      },
      bar: {
        bar1(),
        baz: {
          baz1()
        }
      }
    },
});
Penpal
  .connectToChild({url})
  .promise
  .then(api => {
    api.method1();
    api.foo.foo1();
    api.bar.bar1();
    api.bar.baz.baz1();
  })

Why I think it may be useful: The child may have extensive API (in particular: already existing API, currently exposed to window) as it is in my case. To fit Penpal in my needs I have to flatten that API, which I currently do by flattening the API object with https://www.npmjs.com/package/object-squish and then call methods as api['bar.baz.baz1'](); which is not very handy but it allows preserving already existing structure.

I thought it may be useful to have that baked right into Penpal (with both serialisation and deserialisation off course)

Aaronius commented 6 years ago

I like the idea. I'm a bit concerned at how much it might complicate/bloat the library in relation to the number of consumers that would use the feature. Simplicity and small file size are important. I'd like to see what it looks like with the enhancement added and see if it's worth the cost.

jrencz commented 6 years ago

I see your point. I think It can be implemented in a way that serialiser/deserialiser of methods are configurable functions. This would also allow some other tricks like initialising constructed objects from what comes from Penpal.

If no serialiser/deserialiser are set then a generic one (requiring methods to be flat dictionary) would be used and it's what's there at the moment. It just has to be abstracted out and made configurable.

Anyone interested in passing more complex structures would be able to do that, everyone else won't be bothered with size increase much

Aaronius commented 6 years ago

I like it. I'll play around with the idea sometime unless you or someone else gets to it first.

Aaronius commented 6 years ago

Hey @jrencz, I don't plan on spending time on this. If you'd like to write a PR and it doesn't complicate things much or bloat the size I would entertain it, but can't guarantee it will get merged. Thanks for all your feedback on the issues that have come through so far.

Aaronius commented 3 years ago

Support for this has been published in 6.1.0 thanks to @cdun's contribution.