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

手机游戏开发者 2024-9-30 07:47:46 40 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: "",})

  • 可以看到,这两个graphql范例定义中,都将 Name 写成了 ResponseCommon
  • 这个 Name 对应的就是前面说的 _typename
    1.png
当两个接口(内里的_typename同名)同时存在时就会出错。

2.png
报错如下:

{"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的事儿。这次必须记下来,警觉本身!
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-11-24 08:14, Processed in 0.165519 second(s), 36 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表