在 Graphql 中为 return 相同结果编写动态模式

Write dynamic schema for return same result in Graphql

目前此架构正常工作并提供所需的结果

  type Personal{
    userId:String
    name: String
    email: String
  }
  type Contact{
    mobile_no:String
    email:String
  }
  type Address{
    address:String
    lat:String
    long:String
  }
  getContact(userId: String): Contact
  getPersonal(userId: String): Personal
  getAddress(userId: String): Address

但是我想return

 type Response {
    status: Boolean
    message: String
    data: []
  }

Return 具有状态和消息键的数据,其中数据包含一组联系人、个人和地址对象。

不写 ResponseContact、ResponsePersonal 和 ResponseAddress

我想 return scalar JSON 这样的数据

 scalar JSON
 type Response {
   status: Boolean
   message: String
   data: [JSON]
 }

但是这个schema的问题我不能用graphql第二要点"Ask for what you want" 所需结果

type ResponseAddress {
    status: Boolean
    message: String
    data: [Address]
}
type ResponsePersonal {
    status: Boolean
    message: String
    data: [Personal]
}
type ResponseContact {
    status: Boolean
    message: String
    data: [Contact]
}
getContact(userId: String): ResponseContact
getPersonal(userId: String): ResponsePersonal
getAddress(userId: String): ResponseAddress

不写 ResponseAddress、ResponsePersonal 和 ResponseContact。

类似的东西

type Response {
    status: Boolean
    message: String
    data: [Address|Personal|Contact]
}
getContact(userId: String): Response
getPersonal(userId: String): Response
getAddress(userId: String): Response

当然上面的语法是错误的。

为什么:- 因为我想return这个响应更多的地方并且不想很长的架构。

要点:- 这可能吗?

可以使用接口或联合将多个类型分配给单个字段:

union ResponseData = Address | Personal | Contact

type Response {
    status: Boolean
    message: String
    data: ResponseData
}

请记住,在查询此字段时,客户端将需要利用内联片段来指定为每种可能的类型请求哪些字段:

query {
  getContact {
    status
    message
    data {
      ... on Address {
        # Address field here
      }
      ... on Personal {
        # Personal field here
      }
      ... on Contact {
        # Contact field here
      }
    }
  }
}

您可以查看 the docs 以获得有关如何同时实现联合和接口的详细说明。请记住,您只能创建对象类型的联合,因此如果您需要 returns 列表的响应,则需要至少为响应定义两种类型:

type Response {
  status: Boolean
  message: String
  data: ResponseData
}

type ListResponse {
  status: Boolean
  message: String
  data: [ResponseData]
}

注意:以这种方式使用联合确实会在客户端增加一些复杂性,我会说一般来说,仅仅拥有一个较小的模式是不值得的。像 GraphiQL 和 GraphQL Playground 这样的工具使得使用大型模式对消费者来说变得轻而易举。如果您需要的话,拥有具有冗余类型的大型模式并不是一件坏事。