Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

inheritance - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...