Is it possible to implement multiple interfaces in

2020-04-03 04:49发布

Is it possible to specify a type that implements multiple interfaces within a GraphQL schema? If so, how would this be accomplished?

标签: graphql
3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-04-03 04:57

I think yes, it should be possible as the specification describes on http://facebook.github.io/graphql/June2018/#sec-Interfaces.

Here is the example.

interface NamedEntity {
  name: String
}

interface ValuedEntity {
  value: Int
}

type Person implements NamedEntity {
  name: String
  age: Int
}

type Business implements NamedEntity & ValuedEntity {
  name: String
  value: Int
  employeeCount: Int
}
查看更多
叼着烟拽天下
3楼-- · 2020-04-03 05:13

It seems comma separating the interfaces doesn't work anymore. I had to use "&" instead to make it work (Apollo), see this answer https://stackoverflow.com/a/49521662/1959584

type Something implements First & Second
查看更多
神经病院院长
4楼-- · 2020-04-03 05:17

Yes. As outlined in the spec:

An object type may declare that it implements one or more unique interfaces.

Keep in mind that the resulting object must be a "super-set of all interfaces it implements" -- it must implement all the fields each interface has and these fields cannot conflict. For example, if Interface A and Interface B both have a field called something, the type of that field must be the same for both interfaces in order for an Object Type to implement both interfaces.

Here's a simple example that you can open in CodeSandbox and play around with.

Note: As others have pointed out, using a comma to separate the interfaces is no longer supported -- please use an & (ampersand) instead.

const { ApolloServer, gql } = require("apollo-server");

const typeDefs = gql`
  type Query {
    someAnimal: Animal!
    someBird: Bird!
  }

  interface Bird {
    wingspan: Int!
  }

  interface Animal {
    speed: Int!
  }

  type Swallow implements Animal & Bird {
    wingspan: Int!
    speed: Int!
  }
`;

const resolvers = {
  Query: {
    someAnimal: (root, args, context) => {
      return { wingspan: 7, speed: 24 };
    },
    someBird: (root, args, context) => {
      return { wingspan: 6, speed: 25 };
    }
  },
  Bird: {
    __resolveType: () => "Swallow"
  },
  Animal: {
    __resolveType: () => "Swallow"
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers
});

server.listen().then(({ url }) => {
  console.log(`                                                                    
查看更多
登录 后发表回答