Skip to content

Move from class-transformer to manual JSON<->class instance mapping #55

Description

@heavyrubberslave

class-transformer has several limitations (like for example it needs public constructors on all objects, etc). Alternative is to define proper schemas using Zod Ajv (it's faster) or similar. Also consider sharing DTO types between backend and frontend in separate repo/package and maybe use JSON schema to generate the types.

Then implement a mapper library:

type FromDtoFactory = (dto: DeviceAttributeDTO) => DeviceAttribute<T>;
type ToDtoFactory = () => ;

export class Serializer {

  private List<ToDtoFactory> toDtoFactories = [];
  private List<FromDtoFactory> fromDtoFactories = [];

  static toDTO(classInstance: T): DeviceAttributeDTO {
    return toDtoFactories.get(T)(classInstance);
  }

  static fromDTO<T>(
    dto: unknown,
  ): DeviceAttribute<T> {
    const parsed = DeviceAttributeSchema.parse(dto);
    return fromDtoFactories.get(T)(parsed);
  }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions