mathematic-inc / ts-japi

A highly-modular (typescript-friendly)-framework agnostic library for serializing data to the JSON:API specification
Apache License 2.0
203 stars 16 forks source link

[FR] Mapping Attributes #20

Closed johannesschobel closed 3 years ago

johannesschobel commented 3 years ago

Dear developers,

i recently stumbled upon your jsonapi library because i am strongly considering the use of json:api for my next project at work. However, when reading the docs, i stumbled upon some questions:

Is your feature request related to a problem? *

In the Serializer it is possible to add some projections, which basically describe the attributes that are serialized. Consider the following example:

export const userSerializer = new Serializer<User>('users', {
  projection: {
    email: 1,
    password: 1,
    firstName: 1,
    lastName: 1,
    settings: 1,
  },
});

For my client, however, i would also output a fullName attribute, that is basically generated from the firstname and lastname (i.e., fullName: firstname + ' ' + lastname).

Unfortunately, i did not find any way to add this feature. Do you have any idea how i can manage this?

Furthermore, i find the projection-definition with 1 | 0 | undefined quite unintuitive. I would rather use an approach like in fractal ( https://fractal.thephpleague.com/transformers/ ), where you map your attributes to specific values of the entity

Describe the solution you'd like*

I would like to use something like this:

export class UserSerializer extends Serializer<User> {
  transform(entity: User) {
    id: entity.id,
    email: entity.email,
    firstName: entity.firstName,
    // ...
    fullName: `${entity.firstName} ${entity.lastName}`,
  }
}

Describe alternatives you've considered*

PHP Fractal ( https://fractal.thephpleague.com/transformers/ )

jrandolf commented 3 years ago

Thanks for the issue.

The projection API follows the MongoDB API (which may have been a bad design choice), but nevertheless, won't be changed.

Adding transformers was an idea mentioned in a previous, closed issue (https://github.com/mu-io/ts-japi/issues/14). In conclusion, we want to separate concerns; transformation should take place before serialization and if a different type arises because of that transformation, then create a serializer for that transformed type. See that issue for more information.

johannesschobel commented 3 years ago

Dear @jun-sheaf , thank you very much for your fast response. Also, thanks for pointing to this issue. Initially, when working with the linked php package, both (transformation & serialization) was taken on in one library. I think, those use-cases are tied close together, so i thought it may be a good idea to have both features in one package.

This mapping between class A and class B for sure is possible, but may add additional overhead and boilerplate. However, i will take a closer look at it.

Thank you very much for your time and help