Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Inherit or Extend typeDefs in GraphQL

I have a type User. Users can also be a type TeamMember. The only difference between a User and TeamMember is an added field teamRole: String. So, I’d love to do something like the following to avoid having to redundantly define all the user's fields…

  type User {
    id: ID!,
    name: String,
    (many other field defs)
  }

  type TeamMember extends User  {
    teamRole: String,
  }

Anyone aware of a syntax for this? I thought extend would be the answer, but it seems more like javascript’s prototype

like image 766
Chris Geirman Avatar asked Nov 28 '17 03:11

Chris Geirman


1 Answers

The extend keyword is great if you have a base schema and want to build two or more usable schemas based on it. You can, for example, define a root Query type with queries shared by all schemas, and then extend it within each individual schema to add queries specific to that schema. It can also be used to modularize a schema. However, it's only a mechanism to add functionality to existing types -- it can't be used to create new types.

GraphQL does not inherently support inheritance. There is no syntax that would help you avoid duplication of fields across multiple types.

You can utilize string interpolation to avoid typing out the same fields again and again:

const sharedFields = `
  foo: String
  bar: String
`
const typeDefs = `
  type A {
    ${sharedFields}
  }

  type B {
    ${sharedFields}
  }
`

Barring that, you can also utilize a library like graphql-s2s which allows you to utilize inheritance and generic types. Schemas generated this way still have to be compiled to valid SDL though -- at best, libraries like graphql-s2s just offer some syntactic sugar and a better DX.

Lastly, you can restructure your types to avoid the field duplication altogether at the cost of a more structured response. For example, instead of doing this:

type A {
  a: Int
  foo: String
  bar: String
}

type B {
  b: Int
  foo: String
  bar: String
}

you can do this:

type X {
  foo: String
  bar: String
  aOrB: AOrB
}

union AOrB = A | B

type A {
  a: Int
}

type B {
  b: Int
}
like image 142
Daniel Rearden Avatar answered Sep 23 '22 02:09

Daniel Rearden