Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
butchmarshall opened this issue Oct 6, 2024 · 0 comments

Comments

@butchmarshall
Copy link

butchmarshall commented Oct 6, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant