mathematic-inc / ts-japi

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

[BUG] Optional fields used for relationships fail serialization #46

Closed egmacke closed 2 years ago

egmacke commented 2 years ago

Describe the bug*

Given a model with an optional field, if that field is defined in the serializer as a relationship, and in a specific instance of the model, does not exist, then the serialization fails.

To Reproduce*

class User {
  public id: string;

  constructor(public name: string) {
    this.id = name;
  }
}

class TestDto {
  id: string;

  label: string;

  user1: User;

  user2?: User;

  constructor() {
    this.id = 'id';
    this.label = 'label';
    this.user1 = new User('Alice');
  }
}

const UserSerializer = new Serializer<User>('User');

const TestUser1Relator = new Relator<TestDto, User>(
  async test => test.user1,
  UserSerializer,
  { relatedName: 'user1' }
);

const TestUser2Relator = new Relator<TestDto, User>(
  async test => test.user2,
  UserSerializer,
  { relatedName: 'user2' }
);

const TestSerializer = new Serializer<TestDto>('Test', {
  relators: [TestUser1Relator, TestUser2Relator],
  projection: {
    user1: 0,
    user2: 0
  }
});

const testDto = new TestDto();
TestSerializer.serialize(testDto).then(v => console.log(JSON.stringify(v)));

Produces this error: Relationships must contain at least a link, data, or meta. See https://jsonapi.org/format/#document-resource-object-relationships for more information.

Expected behavior*

When no value is provided in the un-serialized object and that field is optional, the relationship should not be created, and should not throw an error.

jrandolf commented 2 years ago

Hey @egmacke, we've noticed you seem to work quite a bit with ts:japi. Are you interested in helping maintain this project? In favor of gRPC, We no longer use this internally sadly.

egmacke commented 2 years ago

@jun-sheaf we're in the process of adopting JSON API as the standard across the platform I'm currently working on. This library seemed to give the best implementation when we were initially looking and still seems one of the best options out there, there are just a few places where we've struggled to get it to work how we've needed (while still conforming to the spec)

That said - yes I would certainly be open to helping maintain this project! Let me know what I can do (and I'll start putting together a solution for this issue!)