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);
}
}
class-transformer has several limitations (like for example it needs public constructors on all objects, etc). Alternative is to define proper schemas using
ZodAjv (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: