github.com/maeglindeveloper/gqlgen@v0.13.1-0.20210413081235-57808b12a0a0/graphql/id.go (about)

     1  package graphql
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"strconv"
     8  )
     9  
    10  func MarshalID(s string) Marshaler {
    11  	return WriterFunc(func(w io.Writer) {
    12  		io.WriteString(w, strconv.Quote(s))
    13  	})
    14  }
    15  func UnmarshalID(v interface{}) (string, error) {
    16  	switch v := v.(type) {
    17  	case string:
    18  		return v, nil
    19  	case json.Number:
    20  		return string(v), nil
    21  	case int:
    22  		return strconv.Itoa(v), nil
    23  	case int64:
    24  		return strconv.FormatInt(v, 10), nil
    25  	case float64:
    26  		return fmt.Sprintf("%f", v), nil
    27  	case bool:
    28  		if v {
    29  			return "true", nil
    30  		} else {
    31  			return "false", nil
    32  		}
    33  	case nil:
    34  		return "null", nil
    35  	default:
    36  		return "", fmt.Errorf("%T is not a string", v)
    37  	}
    38  }
    39  
    40  func MarshalIntID(i int) Marshaler {
    41  	return WriterFunc(func(w io.Writer) {
    42  		writeQuotedString(w, strconv.Itoa(i))
    43  	})
    44  }
    45  
    46  func UnmarshalIntID(v interface{}) (int, error) {
    47  	switch v := v.(type) {
    48  	case string:
    49  		return strconv.Atoi(v)
    50  	case int:
    51  		return v, nil
    52  	case int64:
    53  		return int(v), nil
    54  	case json.Number:
    55  		return strconv.Atoi(string(v))
    56  	default:
    57  		return 0, fmt.Errorf("%T is not an int", v)
    58  	}
    59  }