541.【GraphQL】_typename千万不要写成一样的

2023-01-05  本文已影响0人  七镜

这个问题我已经经历过两三次了:*graphql 服务端定义接口时,千万不要把每个接口中的_typename写成一样的
在go语言中,graphql 的实现里头, 错误的示例如下:

var responseDimensionReadingType = graphql.NewObject(graphql.ObjectConfig{
    Name: "ResponseCommon",
    Fields: graphql.Fields{
        "code":    &graphql.Field{Type: graphql.Int},
        "content": &graphql.Field{Type: graphql.NewList(dimensionReadingType)},
        "count":   &graphql.Field{Type: graphql.Int},
        "msg":     &graphql.Field{Type: messageType},
    },
    Description: "",
})
var responseDimensionWritingType = graphql.NewObject(graphql.ObjectConfig{
    Name: "ResponseCommon",
    Fields: graphql.Fields{
        "code":    &graphql.Field{Type: graphql.Int},
        "content": &graphql.Field{Type: graphql.NewList(dimensionWritingType)},
        "count":   &graphql.Field{Type: graphql.Int},
        "msg":     &graphql.Field{Type: messageType},
    },
    Description: "",
})

当两个接口(里面的_typename同名)同时存在时就会出错。


触发报错

报错如下:


{"data":null,"errors":[{"message":"Variable \"$from_id\" cannot be non-input type \"String!\".","locations":[{"line":1,"column":34}]},{"message":"Unknown type \"String\".","locations":[{"line":1,"column":34}]},{"message":"Variable \"$from_nickname\" cannot be non-input type \"String!\".","locations":[{"line":1,"column":59}]},{"message":"Unknown type \"String\".","locations":[{"line":1,"column":59}]},{"message":"Variable \"$content\" cannot be non-input type \"String!\".","locations":[{"line":1,"column":78}]},{"message":"Unknown type \"String\".","locations":[{"line":1,"column":78}]},{"message":"Variable \"$from_id\" of type \"\" used in position expecting type \"String!\".","locations":[{"line":1,"column":24},{"line":3,"column":14}]},{"message":"Variable \"$content\" of type \"\" used in position expecting type \"String!\".","locations":[{"line":1,"column":68},{"line":4,"column":14}]},{"message":"Variable \"$from_nickname\" of type \"\" used in position expecting type \"String!\".","locations":[{"line":1,"column":43},{"line":5,"column":20}]}]}

调查这个问题时,感觉离谱之处在于:我随便保留两个接口中的其中一个,都不会有问题,两个接口同时出现才会报错。

记忆中,第一次出现这个问题,我debug,debug了一天没找着原因,后来还是整整回滚了一个版本的代码才解决;第二次遇到这个问题,也是花了好久才知道是_typename的事儿。这次必须记下来,警醒自己!

上一篇下一篇

猜你喜欢

热点阅读