json - 无法在 gqlgen 中生成标量 JSON

标签 json go graphql scalar gqlgen

我有一个 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
}

关于json - 无法在 gqlgen 中生成标量 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70955985/

相关文章:

go - 使用 Scanner 处理每行多个标记的更好方法?

google-app-engine - 为什么调用此方法会导致我的应用超出免费配额?

用于文件下载的 GraphQL 端点

jQuery、JSON 数组推送

通过对象的 JavaScript 值求和

http - Golang http.PostParam 未在响应中显示所有 Cookie

c# - 如何在 GraphQL HotChocolate 中实现订阅?

graphql - 使用 NEXT.js 和 Apollo 客户端 2 配置订阅

python - 将逗号分隔的项目拆分为 scrapy 中的列表

javascript - 来自 JSON 数据的 Google map 标记 - "Failed to load resource"