maritz / nohm

node.js object relations mapper (orm) for redis
http://maritz.github.io/nohm/
MIT License
500 stars 64 forks source link

defaultValue functions always being executed in constructor #117

Open maritz opened 6 years ago

maritz commented 6 years ago

Currently the defaultValue is always set during the execution of the constructor for each property.

When using the defaultValue function to create cryptographically strong tokens (as an example) this produces a lot of overhead on each model invocation.

One possible way to reduce this is to only set the defaultValue when it's required. Meaning on save() or property access.

Another way could be to optionally not invoke defaultValue functions in the constructor via argument, then pass this argument from all static shortform methods that create an instance (.load(), .loadMany(), .findAndLoad(), .remove()).

For now a possible work-around is to extend save() like this:

  // typescript example
  protected async save() {
    if (!this.id) {
      this.property('loginToken', (await randomBytes(128)).toString('hex'));
    }
    return super.save();
  }