rawmodel/framework

Error when try to populate a model with a Function Field

dmunozgaete opened this issue · 2 comments

Hi:

when you call the populate method, in a schema model with Function field type, it's simply fails =(, because the JSON.stringify(field) call before setting the value.

Example:

//CheckoutButtonRenderModel.ts
import { Model } from 'rawmodel';

// defining a basic model
class CheckoutButtonRenderModel extends Model {
    public payment: Function;

    public constructor(data = <any>{}) {
        super(data);

        this.defineField('payment', {
        
        });

        this.populate(data);
    }
};
export { CheckoutButtonRenderModel };
let buttonModel = new CheckoutButtonRenderModel(model);
		buttonModel
			.validate()
			.then((r) => {
			},
			(err) => {
				console.error("Validation Error ", buttonModel.collectErrors()[0].errors);

			});

TLDR:

the error happens when you have a field with Function type, the library try to stringify a function type and the error show as:

/*
  * Deeply applies data to the fields.
  */

  public populate (data = {}): this {
    Object.keys(data)
      .filter((n) => !!this._fields[n])
      .forEach((name) => this[name] = serialize(data[name]));

    return this;
  }

and in the utils.ts

/*
* Returns a duplicated data object (useful to remove data bindings).
*/

export function serialize (data: any) {
  return JSON.parse(JSON.stringify(data));
}

You are right. This module depends on ValidatableJS for type casting but skips the Function field type intentionally to keep separation between the data and instance methods. I guess I need to fix the documentation for this - thanks!

Please try using field value transformations instead. You could also use your own data type as explained in the readme (see the defineType method).

Thanks for pointing this out. I updated the documentation.