0

我有一个 GQL 方案:

extend type MyType @key(fields: "id") {
  id: ID! @external
  properties: JSON @external
  myField: String! @requires(fields: "properties")
}
scalar JSON

在图形/模型/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/gqlgen 生成错误:

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,但对于阿波罗联邦,该字段必须称为 JSON。

4

1 回答 1

0

应该将 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
}

于 2022-02-02T14:10:51.243 回答