0

采取这个方案:

union Vehicle = Airplane | Car

type Airplane {
     title: String
     wingSpan: Int
}

type Car {
    title: String
    wheels: Int
}

type Person {
    vehicle: [Vehicle!]
}

这个查询:

person {
     vehicles {
         ... on Car {
            title
            wheels 
         }
        ... on Airplane {
            title
            wingSpan 
         }
     }
}

这些解析器:

// vehicle-resolver.js
export default {
    Vehicle: {
        __resolveType(obj) {
            if (obj.wheels)  {
                return "Car"
            } else {
                return "Airplane"
            }
        }
    }
}

// person-resolver.js
export default {
    Person: {
        vehicles(obj, args, context) {
            // Am I resolving a car or an airplane now - or even both?
            // I need to ask my CarService with `obj.personId` or my AirplaneService with `obj.personId` also, but I only want to query it if the query is asking for it.
        }
    }
}

Person -> vehicles(...)不确定什么时候应该查询我的不同服务以获得汽车和飞机?在该方法中,我不知道我们正在解决哪种类型。

4

1 回答 1

1

您将无法知道您的 Union您的解析器中解析为什么类型,vehicles因为该__resolveType字段Vehicle实际上取决于它从该解析器接收的数据。

听起来您希望客户端能够请求服务器查询人员的汽车或他/她的飞机或两者,然后让服务器采取相应的行动。这通常通过将参数传递给字段来完成,例如:

# type definitions
type Person {
  vehicles(type: VehicleType): [Vehicle!]
}

enum VehicleType {
  CAR
  AIRPLANE
}

//resolver
vehicles(obj, { type }, context) {
  if (type === 'CAR') // fetch and return cars
  if (type === 'AIRPLANE') // fetch and return planes
  // otherwise fetch and return both
}

type: Car从客户的角度来看,必须将类型标识为参数( )然后再在条件片段( )中标识类型可能有点多余... on Car,但这是最简单的解决方案。

或者,您可以使用文档较少的路径,查看客户端在每个请求的基础上实际请求了哪些字段。这可以通过深入研究传递给解析器函数(info)的第四个参数来完成。我认为使用 Apollo,您应该能够获取如下字段的列表:

info.fieldNodes[0].selectionSet.selections.map(s => s.typeCondition.name.value)

然后,您可以检查请求的类型并让您的解析器采取相应的行动。

但是,前一种方式(即向字段添加类型参数)还有一个额外的好处。作为客户,如果我想将查询从取车更改为取飞机,我不想存储两个(或更多)不同的查询,并且必须根据我想要获取的类型在它们之间切换.

在客户端的上下文中,如果类型是可变的,它可能只是一个在应用程序状态中持久化的变量。那么,作为客户,我宁愿将该变量与我的查询一起传递。如果我的变量改变了,我的查询结果也会改变,但我不必担心改变查询本身(即它可以包含两种类型的条件片段)。

于 2017-09-20T05:18:53.483 回答