Is it possible to implement multiple interfaces in

2020-04-03 04:12发布

问题:

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

回答1:

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(`              
                            
标签: graphql