GraphQL.js 具有自定义标量类型的突变

GraphQL.js mutation with custom scalar type

我在 GraphQL 中有一个基于 GeoJSON 的 API,我正在尝试对其进行突变。我正在使用 graphql-geojson 中的一些类型。输入类型和变异的定义如下:

# ... from graphql-geojson ...
var CoordinatesScalar = new ScalarType({
 name: 'GeoJSONCoordinates',
 description: 'A (multidimensional) set of coordinates following x, y, z order.',
 serialize: coerceCoordinates,
 parseValue: coerceCoordinates,
 parseLiteral: parseCoordinates})


# ... schema.js ...
var waypointInputType = new GraphQLInputObjectType({
  name: 'WaypointInput',
  fields: {... schema.js ...]
var waypointInputType = new GraphQLInputObjectType({
  name: 'WaypointInput',
  fields: {
    type: {type: GraphQLString},
    coordinates: {type: CoordinatesScalar}
  }
});
var missionInputType = new GraphQLInputObjectType({
  name: 'MissionInput',
  fields: () => ({
    waypoints: {type: waypointInputType},
    max_groundspeed: {type: GraphQLFloat}
  })
});

var createMission = {
  type: missionType,
  description: 'Create a new mission.',
  args: {
    mission: {type: missionInputType}
  },
  resolve(value, {mission}) {
    return models.Mission.create(mission).then(mission => mission);
  }
};

# ... in schema definition ...
mutation: new GraphQLObjectType({
name: 'RootMutationType',
fields: {
  createMission
}
})

在 graphiql 中,我发布了一个像

这样的突变
mutation {
  createMission(mission: {
    waypoints: {
      type: "LineString",
      coordinates: [[1, 2], [3, 4]]
    }
  }) {
    id
  }
}

保存一些新坐标并查询创建的任务 ID。但是,graphql 会抛出 Argument mission has invalid value [...] coordinates: expected type GeoJSONCoordinates, found [[1, 2], [3, 4]] 的错误。我可以在坐标中放置任意字符串,但嵌套数组似乎不起作用。使用引号中的嵌套数组,我在查询时得到一个字符串:

{
 "waypoints": {
          "type": "LineString",
          "bbox": null,
          "coordinates": "[[1, 2], [3, 3]]"
      }
}

我可以使用CoordinatesScalar作为输入类型,还是需要定义一个CoordinatesScalar可以专门解析的输入类型?

如果您使用完整的语法来发出突变,您可以指定输入的类型:

mutation CreateMission(mission: MissonInput) {
  createMission(mission: $mission) {
    id
  }
}

那么你可以提供变量:

{
  mission: {
    waypoints: {
      type: "LineString",
      coordinates: [[1, 2], [3, 4]]
    }
  }
}

我不确定这是否能解决问题,请告诉我! :)