4

I would like to know how safe is the usage of setter and getter properties from model class.

This is already being used in loopback user model and can be seen here: User Code

Why is this not documented anywhere? Can we use it?

mitsos1os
  • 2,170
  • 1
  • 20
  • 34

2 Answers2

3

I'm still looking for "official" documentation, but our primary engineer documented it in another SO answer here: https://stackoverflow.com/a/24253273/52160.

If I can find official support in the docs I'll update the question.

Community
  • 1
  • 1
Raymond Camden
  • 10,661
  • 3
  • 34
  • 68
  • Thanks for your answer! I have already seen this. I wondered if someone could officially verify it... Anyway, I will keep the question open, until it completely verified.. – mitsos1os May 05 '16 at 15:27
1

Actually, with some deeper digging, I found that this is actually used and defined in the ModelBuilder class of loopback-datasource-juggler module. It is defined here

ModelClass.setter = {};

And used here

Object.defineProperty(ModelClass.prototype, propertyName, {
  get: function() {
    if (ModelClass.getter[propertyName]) {
      return ModelClass.getter[propertyName].call(this); // Try getter first
    } else {
      return this.__data && this.__data[propertyName]; // Try __data
    }
  },
  set: function(value) {
    var DataType = ModelClass.definition.properties[propertyName].type;
    if (Array.isArray(DataType) || DataType === Array) {
      DataType = List;
    } else if (DataType === Date) {
      DataType = DateType;
    } else if (DataType === Boolean) {
      DataType = BooleanType;
    } else if (typeof DataType === 'string') {
      DataType = modelBuilder.resolveType(DataType);
    }

    var persistUndefinedAsNull = ModelClass.definition.settings.persistUndefinedAsNull;
    if (value === undefined && persistUndefinedAsNull) {
      value = null;
    }

    if (ModelClass.setter[propertyName]) {
      ModelClass.setter[propertyName].call(this, value); // Try setter first
    } else {
      this.__data = this.__data || {};
      if (value === null || value === undefined) {
        this.__data[propertyName] = value;
      } else {
        if (DataType === List) {
          this.__data[propertyName] = DataType(value, properties[propertyName].type, this.__data);
        } else {
          // Assume the type constructor handles Constructor() call
          // If not, we should call new DataType(value).valueOf();
          this.__data[propertyName] = (value instanceof DataType) ? value : DataType(value);
        }
      }
    }
  },
  configurable: true,
  enumerable: true,
});

So it is probably implemented, but not documented...

mitsos1os
  • 2,170
  • 1
  • 20
  • 34