Skip to content

Implement a plugin that is able to add class-transformer decorators to targeted classes #855

Open
@butchmarshall

Description

@butchmarshall

The class-transformer package implements the plainToClass method, which as its name suggests is used to map a plain object to a class.

When querying GraphQL, often a subset of your objects query types will align 1-1 with a mutations input types, for example:

type User {
  id: String
  name: String
}

input UserInput {
  id: String
  name: String
}

mutation UpsertUser($input: UserInput!) {
  upsertUser(input: $input) {
    id
  }
}

A common access pattern is data is queried from a server and then directly mapped into a form data input type. This is can be easily automated using the plainToClass helper.

Unfortunately, the default behaviour is to set all properties from the plain object, even those which are not specified in the class.

This behaviour causes issues, specifically in this example the setting of __typename on the input, which is in the query return result but not supported by the input.

To better align with the behaviour needed for GraphQL, excludeExtraneousValues: true can be set, but in order to work each class property must be decorated with @Expose() and nested objects must be decorated with @Type(() => <NestedObjectClassHere>)

Once the classes are property decorated, the following code will work as expected.

import { plainToClass } from 'class-transformer';

const values = plainToClass(
  UpsertUserInput,
  user.data?.user,
  {
    excludeExtraneousValues: true,
  }
);

const {
  control,
  handleSubmit,
  formState: { errors },
  setError,
} = useForm<UpsertUserMutationVariables['input']>({
  values,
});

In order to decorate generated GraphQL input types a plugin must be created to implement this behaviour.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions