【问题标题】:Why graphql type relations returns null values?为什么 graphql 类型关系返回空值?
【发布时间】:2021-03-09 09:36:05
【问题描述】:

我有 SHIPS 的 schema.js

// Ships
const ShipType = new GraphQLObjectType({
  name: "Ships",
  fields: () => ({
    ship_id: { type: GraphQLString },
    ship_name: { type: GraphQLString },
    home_port: { type: GraphQLString },
    ship_type: { type: GraphQLString },
    year_built: { type: GraphQLInt },
    position: { type: ShipPositionType },
    active: { type: GraphQLBoolean }
  })
})

// Ship positions
const ShipPositionType = new GraphQLObjectType({
  name: "ShipPositions",
  fields: () => ({
    latitude: { type: GraphQLFloat },
    longitude: { type: GraphQLFloat }
  })
});

在 ShipType 我添加了一个新字段“位置”,它将返回 ShipPositionType

这是我到目前为止返回的内容

// get ships
    ships: {
      type: new GraphQLList(ShipType),
      resolve(parent, args) {
        return axios.get('https://api.spacexdata.com/v3/ships')
          .then(res => res.data);
      }
    }

【问题讨论】:

  • 如果没有从 axios/ships 响应返回(可能不是),则需要额外的位置解析器

标签: axios graphql react-apollo apollo-client apollo-server


【解决方案1】:

shipType 中的 position 字段需要有一个解析器,在解析器中,您根据与 ShipPositionType ship_id 匹配的 ShipType ship_id 返回船舶数据。即(return data.find(ship => ship.shid_id === parent.ship_id ))。所以首先在 ShipPositionType 对象中添加一个 ship_id 字段。

Something like this

// Ships
const ShipType = new GraphQLObjectType({
  name: "Ships",
  fields: () => ({
    ship_id: { type: GraphQLString },
    ship_name: { type: GraphQLString },
    home_port: { type: GraphQLString },
    ship_type: { type: GraphQLString },
    year_built: { type: GraphQLInt },
    position: {
            type: ShipPositionType,
            resolve(parent,args) {
             return data.find(data => data.ship_id === parent.ship_id)}
           },
     active: { type: GraphQLBoolean }
  })
})

//You need to add a ship_id field here too
// Ship positions
const ShipPositionType = new GraphQLObjectType({
  name: "ShipPositions",
  fields: () => ({
    ship_id: {type: {GraphQLString},
    latitude: { type: GraphQLFloat },
    longitude: { type: GraphQLFloat }
  })
});

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 2018-11-25
    • 2019-07-11
    • 2015-06-26
    • 2018-02-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多