2

I have a GQL scheme:

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

In 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)
}

But when I run go run github.com/99designs/gqlgen generate error:

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

I just need to get map[string]interface{} which called JSON. I knew there's scalar Map, but for apollo federation that field must be called JSON.

user8439944
  • 73
  • 1
  • 7
  • It should be fixed at tip, try with `github.com/99designs/gqlgen@master` – blackgreen Feb 02 '22 at 13:23
  • You can use the built-in [`Map` scalar](https://gqlgen.com/reference/scalars/#map) defined by gqlgen for this type. All you have to do is declare the scalar type in the GraphQL schema. – Henry Woody Aug 23 '22 at 20:45

1 Answers1

2

it's should to replace MarshalGQL to MarshalJSON like:

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
}

user8439944
  • 73
  • 1
  • 7