15

Suppose I have the following Records defined using Immutable.js:

var Address = Immutable.Record({street: '', city: '', zip: ''});
var User = Immutable.Record({name: '', address: new Address()});

How do I convert plain javascript object into the User record? I tried the following but it does not produce the expected output:

var user = new User({name: 'Foo', address: {street: 'Bar', city: 'Baz'}});
// => Record { "name": "Foo", "address": [object Object] }

I am aware that it is possible to explicitly create the Address record:

var user = new User({name: 'Foo', address: new Address({street: 'Bar', city: 'Baz'})});
// => Record { "name": "Foo", "address": Record { "street": "Bar", "city": "Baz", "zip": "" } }

But that is not solution I am looking for. Imagine you have Records nested several levels deep and want to store/retrieve the data as JSON (e.g. in database). I would like to use the actual User record structure as a schema information for recreating the nested records. Or is there a better way to represent nested and structured immutable data?

dkl
  • 3,850
  • 2
  • 27
  • 26
  • 2
    You could check the `reviver` argument in `Immutable.fromJs`, see http://stackoverflow.com/questions/28639878/how-to-create-a-map-of-records-from-a-javascript-raw-object-with-immutable-js – OlliM Apr 23 '15 at 09:25
  • 1
    To make the question clearer you should state that you want `new User({name: 'Foo', address: {street: 'Bar', city: 'Baz'}}).address instanceof Address` to be true. – Andy Dec 20 '16 at 03:42

2 Answers2

10

The intended use of Record structure isn't to verify the structure of provided data, just to determine set of keys that are allowed and provide default values if they're not given.

So using your example, if you initialize the record without providing Address, you will get the proper Immutable.Record object for Address:

var user = new User({name: 'Foo'});
// => Record { "name": "Foo", "address": Record { "street": "", "city": "", "zip": "" } }

One hackish way to achieve what you want would be to write a wrapper on Immutable.fromJS method with custom reviver function:

Immutable.Record.constructor.prototype.fromJS = function(values) {
  var that = this;
  var nested = Immutable.fromJS(values, function(key, value){
    if(that.prototype[key] && that.prototype[key].constructor.prototype instanceof Immutable.Record){return that.prototype[key].constructor.fromJS(value)}
    else { return value }
  });
  return this(nested);
}

Then you can use it like this:

var user = User.fromJS({name: 'Foo', address: {street: 'Bar', city: 'Baz'}});

// => User { "name": "Foo", "address": Record { "street": "Bar", "city": "Baz", "zip": "" } }

However if you want to have proper checking your data structures, I would recommend using Immutable.js together with some static type-checker, like http://flowtype.org/ or http://www.typescriptlang.org/

Arek Flinik
  • 719
  • 6
  • 9
  • 3
    Actually my intent was not to verify the structure of the data but to hide the fact that the data passed to child components is immutable. When you pass Immutable.Map to child component, it must be aware of it and use data.get('foo') instead of data.foo. I tried to workaround this using Record, which defines the object properties, so that the child component (that just renders the data) can simply use data.foo without caring whether the data is immutable or not. – dkl Apr 24 '15 at 16:50
  • The real problem is to automatically deserialize the `address` from plain JSON into an `Address` record in the `User` constructor. – Andy Dec 20 '16 at 03:39
  • This is smart. I liked it a lot. Then I discovered that since `Immutable.fromJS` is bottom-to-top (leaves first) it cannot be used for deeply nested structures :( – Robin Pokorny Oct 16 '17 at 12:36
9

You can make User subclass the Record definition and parse address in the constructor:

import {Record} from 'immutable'

const Address = Record({street: '', city: '', zip: ''});
class User extends Record({name: '', address: new Address()}) {
  constructor({name, address} = {}) {
    super({name, address: new Address(address)})
  }
}

const user = new User({
  name: 'Andy',
  address: {
    street: 'wherever',
    city: 'Austin',
    zip: 'TX'
  }
})

console.log(user)
console.log('user.address instanceof Address:', user.address instanceof Address)

const user2 = new User({name: 'Bob'})

console.log(user2)
console.log('user2.address instanceof Address:', user2.address instanceof Address)

Output:

User { "name": "Andy", "address": Record { "street": "wherever", "city": "Austin", "zip": "TX" } }
user.address instanceof Address: true
User { "name": "Bob", "address": Record { "street": "", "city": "", "zip": "" } }
user2.address instanceof Address: true
Andy
  • 7,885
  • 5
  • 55
  • 61
  • What about `List`? – Victor Queiroz Mar 29 '17 at 04:06
  • @VictorQueiroz depending on where you mean the list is (`Record` containing a `List`? `List` of `Record`s?) it might involve a combination of this and the `reviver` function mentioned in the above answer. – Andy Mar 29 '17 at 18:17