dfahlander/typeson

Doesn't seem to work on nested types

Closed this issue · 1 comments

I'm not sure if this I'm missing something but it seems that nested types don't work.

Here's an example:

const Typeson = require('typeson')

class Parent {
  constructor(data) {
    this.children = data.children || []
  }
}

class Child {
  constructor() {
    this.name = 'foo'
  }
}

const typeson = new Typeson().register({
  Parent: [
    instance => instance instanceof Parent,
    instance => JSON.stringify(instance),
    data => new Parent(JSON.parse(data))
  ],
  Child: [
    instance => instance instanceof Child,
    instance => JSON.stringify(instance),
    data => new Child(JSON.parse(data))
  ]
})

const parent = new Parent({
  children: [new Child(), new Child()]
})

console.dir(typeson.revive(typeson.encapsulate(parent)), { depth: null })

In the above example I expect this output:

Parent { children: [ Child { name: 'foo' }, Child { name: 'foo' } ] }

but I'm getting instead:

Parent { children: [ { name: 'foo' }, { name: 'foo' } ] }

so it seems that inner types (in the case the children) are not instantiated using the registered type.

Change your parent registration to this:

Parent: [
    instance => instance instanceof Parent,
    instance => instance.children,
    data => new Parent({children: data})
  ]

This approach can work because Typeson must have the children passed on such that they are not already serialized by the time it gets to them (btw, plain objects will be JSON-serialized anyways)--but without being cyclic either (i.e., you could not just have your replacer as instance => instance).