5

I'd like to encrypt fields similar to this example with mongoose: https://gist.github.com/kljensen/7505729

The code in the above link maps a field to a custom decrypt() function for get and an encrypt() function for set.

This causes the plain text value to be encrypted when saved, and decrypted when retrieved.

How would I override getters and setters for a model property in Loopback?

Coder1
  • 13,139
  • 15
  • 59
  • 89

1 Answers1

7

You can set up setter and getter as follows:

<Model>.setter['myProp'] = function(val) {};

See an example in LoopBack's common/models/user.js

Miroslav Bajtoš
  • 10,667
  • 1
  • 41
  • 99
Raymond Feng
  • 1,516
  • 9
  • 5
  • Thanks Raymond, This gets me working with the setter correctly, but I cannot get the getter to work. I grepped the source and can't find any good examples of that. Is there anything examples for getter you can think of? – Coder1 Jun 18 '14 at 00:20
  • Once I updated loopback to the latest, the `getter` worked as expected by simply returning a string. Thanks for getting me on track! – Coder1 Jun 18 '14 at 06:47
  • @Tom I have fixed the link. – Miroslav Bajtoš Nov 10 '16 at 11:54
  • About example in User model: email setter use `this.$email = value` instead of `this.email = value` to avoid name conflicts. Here is a special hotfix in the Loopback core for this: https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/model-builder.js#L615 – countTheRow Mar 18 '19 at 18:32