登录
首页 >  Golang >  Go问答

gqlgen 中未能生成 JSON 标量类型

来源:stackoverflow

时间:2024-02-09 20:33:23 194浏览 收藏

你在学习Golang相关的知识吗?本文《gqlgen 中未能生成 JSON 标量类型》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我有一个 gql 方案:

extend type mytype @key(fields: "id") {
  id: id! @external
  properties: json @external
  myfield: string! @requires(fields: "properties")
}
scalar json

在 graph/model/model.go 中:

package model

import (
    "encoding/json"
    "fmt"
    "io"
    "strconv"
    "strings"
)

type json map[string]interface{}

// unmarshalgql implements the graphql.unmarshaler interface
func (b *json) unmarshalgql(v interface{}) error {
    *b = make(map[string]interface{})
    bytedata, err := json.marshal(v)
    if err != nil {
        panic("fail while marshal scheme")
    }
    tmp := make(map[string]interface{})
    err = json.unmarshal(bytedata, &tmp)
    if err != nil {
        panic("fail while unmarshal scheme")
        //return fmt.errorf("%v", err)
    }
    *b = tmp
    return nil
}

// marshalgql implements the graphql.marshaler interface
func (b json) marshalgql(w io.writer) {
    bytedata, err := json.marshal(b)
    if err != nil {
        panic("fail while marshal scheme")
    }
    _, _ = w.write(bytedata)
}

但是当我运行 go run github.com/99designs/gqlgengenerate 错误:

generating core failed: type.gotpl: template: type.gotpl:52:28: executing "type.gotpl" at <$type.Elem.GO>: nil pointer evaluating *config.TypeReference.
GOexit status 1

我只需要获取调用 json 的 map[string]interface{} 。我知道有标量 map,但对于 apollo federation,该字段必须称为 json。


正确答案


应该将 marshalgql 替换为 marshaljson,如下所示:

type JSON map[string]interface{}

func MarshalJSON(b JSON) graphql.Marshaler {
    return graphql.WriterFunc(func(w io.Writer) {
        byteData, err := json.Marshal(b)
        if err != nil {
            log.Printf("FAIL WHILE MARSHAL JSON %v\n", string(byteData))
        }
        _, err = w.Write(byteData)
        if err != nil {
            log.Printf("FAIL WHILE WRITE DATA %v\n", string(byteData))
        }
    })
}

func UnmarshalJSON(v interface{}) (JSON, error) {
    byteData, err := json.Marshal(v)
    if err != nil {
        return JSON{}, fmt.Errorf("FAIL WHILE MARSHAL SCHEME")
    }
    tmp := make(map[string]interface{})
    err = json.Unmarshal(byteData, &tmp)
    if err != nil {
        return JSON{}, fmt.Errorf("FAIL WHILE UNMARSHAL SCHEME")
    }
    return tmp, nil
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>