Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing nested Records in Immutable.js

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?

like image 926
dkl Avatar asked Apr 21 '15 05:04

dkl


1 Answers

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/

like image 151
Arek Flinik Avatar answered Sep 22 '22 10:09

Arek Flinik