美文网首页
541.【GraphQL】_typename千万不要写成一样的

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

作者: 七镜 | 来源:发表于2023-01-05 07:49 被阅读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
      _typename

    当两个接口(里面的_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的事儿。这次必须记下来,警醒自己!

    相关文章

      网友评论

          本文标题:541.【GraphQL】_typename千万不要写成一样的

          本文链接:https://www.haomeiwen.com/subject/wgekcdtx.html