rawmodel / framework

Strongly-typed JavaScript object with support for validation and error handling.
https://rawmodel.github.io/framework/
MIT License
142 stars 16 forks source link

Support for optional data formatting based on the serialization strategy #82

Open BerciTheBeast opened 4 years ago

BerciTheBeast commented 4 years ago

I propose the addition of optional formatting of values based on the serialization strategy that was used.

Example: In model:

@prop(...)
public firstName: string;

@prop({
...
    serializable: ['short', 'full'],
    //some formatting logic based on serialization
})
public lastName: string;

Usage:

user.serialize('short'); // {firstName: 'John', lastName: 'S.'}
user.serialize('full'); // {firstName: 'John', lastName: 'Smith'}
xpepermint commented 4 years ago

Thanks for the proposal. Do you have a use case for this? I'm not sure if that's a good practice to have getters with "unexpected" results. For what you describe I would suggest implementing your own getter for a specific field, adding "transform field" function or simply having 2 fields.

Workaround 1:

class User {
  @prop({
    serializable: ['short', 'full'],
    getter() { },
  })
  public lastName: string;
  public shortenLastNameFormat() {...}
}
const user = new User();
user.shortenLastNameFormat();
user.serialize();

Workaround 2:

class User {
  @prop({
    serializable: ['short', 'full'],
    getter() { },
  })
  public lastName: string;
  public serialize(f) {
    const s = super.serialize(f);
    if (f == 'short') s.firstName = 'X';
    return s;
  }
}
const user = new User();
user.shortenLastNameFormat();
user.serialize();
BerciTheBeast commented 4 years ago

A simple use case would be if we wanted to format the data based on certain permissions.

Let's say, for example, 2 types of people can access a list of objects "person" with the property lastName. One type is "supervisor", the other type is "user".

The supervisor should be able to see the full lastName - so they can perform supervision efficiently, while user should only be able to see the first letter, to prevent them from looking up the "person" in question.


Aside from that, thank you for the workarounds.

xpepermint commented 4 years ago

I see. Let me think about how would be the right way to handle this case.