spring-projects / spring-graphql

Spring Integration for GraphQL
https://spring.io/projects/spring-graphql
Apache License 2.0
1.52k stars 299 forks source link

Class Name differs from Schema Object name #466

Closed saintcoder closed 2 years ago

saintcoder commented 2 years ago

If the graphql schema object name differs from class name, the controller @QueryMapping works but @SchemaMapping does not work. If change graphql schema name to same as class name then SchemaMapping works. Do we class level annotation to map a class to graphql object name for "SchemaMapping" to work?

nilshartmann commented 2 years ago

If your types doesn't match, you can specify the typeName argument at your @SchemaMapping function:

type Person {
  name: String
}
@Controller
class PersonController {

  @SchemaMapping(typeName="Person")
  public String name(PersonEntity source) {
    // Resolve 'name' field on GraphQL 'Person' type
  }
}

You can also specify SchemaMapping with typeName on class level. In this case all source objects are assumed to be of GraphQL type with your typename unless specified otherwise:

@Controller
@SchemaMapping(typeName="Person")
class PersonController {

  // 'name' field on GraphQL Type 'Person' is mapped here
  // (typeName used from typeName of classLevel annotation)
  @SchemaMapping
  public String name(PersonEntity source) {
    // ...
  }

  // 'city' field on GraphQL Type 'Address' is mapped here
  @SchemaMapping(typeName="Address")
  public String city(AddressEntity source) {
    // ...
  }
}

Hope that helps!

saintcoder commented 2 years ago

Thank you @nilshartmann. Any reason why add configuration "typeName" on "Controller" rather than entity object?

rstoyanchev commented 2 years ago

@SchemaMapping is already built for this and a logical place for it. It externalizes the mapping, making it independent from the entity object, which you may not always be able to change, or which may need to be used in code that doesn't depend on GraphQL and spring-graphl. Furthermore, @SchemaMapping is just one programming model that is self-contained, but there are others like QueryDsl, QueryByExample, etc that may be used in parallel.