是否可以在GraphQL中实现多个接口?

pur*_*dox 8 graphql

是否可以指定在GraphQL模式中实现多个接口的类型?如果是这样,这将如何实现?

Dan*_*den 16

当然,这是一个简单的例子,你可以插入Launchpad并玩弄:

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(` Server ready at ${url}`);
});
Run Code Online (Sandbox Code Playgroud)


Mik*_*ank 10

似乎逗号分隔接口不再起作用了.我不得不使用"&"来使其工作(Apollo),请参阅此答案/sf/answers/3466516371/

type Something implements First & Second
Run Code Online (Sandbox Code Playgroud)


gip*_*any 5

我认为是的,应该可以按照规范在http://facebook.github.io/graphql/June2018/#sec-Interfaces中描述的方式进行操作。

这是例子。

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
}
Run Code Online (Sandbox Code Playgroud)