Skip to content

JS client: Model methods should be added to prototype #2044

@delenius

Description

@delenius

In the generated model classes, each instance contains the methods constructFromObject, toJson, plus getters and setters for all the fields. Currently, these methods are added as anonymous functions to each instance. Meaning, if I have 100 instances of some class, I have 100 copies of each of the methods.

These should be added to the class's prototype instead. For example, instead of (current version)

var Person = function Person(name) {
  var self = this;
  self['name'] = name;
  self['age'] = age;
  self.constructFromObject = function(data) {
      if (!data) {
        return this;
      }
      self['name'] = ApiClient.convertToType(data['name'], 'String');
      return this;
  }
  self.getName = function() {
    return self['name'];
  }
  self.setName = function(name) {
    self['name'] = name;
  }
  self.toJson = function() {
    return JSON.stringify(self);
  }
}

it should generate (new version):

var Person = function Person(name) {
  this['name'] = name;
}

Person.prototype.constructFromObject = function(data) {
  if (!data) {
    return this;
  }
  this['name'] = ApiClient.convertToType(data['name'], 'String');
  return this;
}

Person.prototype.getName = function() {
  return this['name'];
}

Person.prototype.setName = function(name) {
  this['name'] = name;
}

Person.prototype.toJson = function() {
  return JSON.stringify(this);
}

Two additional comments:

  1. It would be nice to be able to omit the getters and setters entirely, as they cause a lot of bloat that is not desired in many cases.
  2. The toJson prototype is the same for every model, and could be moved to a higher level prototype:
var ApiModel = function(){}
ApiModel.prototype.toJson = function() { return JSON.stringify(this); }

var Person = function Person(name) {
  ApiModel.call(this);
  this['name'] = name;
}

// all the Person prototype function follow like before, except toJson

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions