...
1 package graphql
2
3 import (
4 "context"
5 "io"
6 )
7
8 var (
9 nullLit = []byte(`null`)
10 trueLit = []byte(`true`)
11 falseLit = []byte(`false`)
12 openBrace = []byte(`{`)
13 closeBrace = []byte(`}`)
14 openBracket = []byte(`[`)
15 closeBracket = []byte(`]`)
16 colon = []byte(`:`)
17 comma = []byte(`,`)
18 )
19
20 var (
21 Null = &lit{nullLit}
22 True = &lit{trueLit}
23 False = &lit{falseLit}
24 )
25
26 type Marshaler interface {
27 MarshalGQL(w io.Writer)
28 }
29
30 type Unmarshaler interface {
31 UnmarshalGQL(v interface{}) error
32 }
33
34 type ContextMarshaler interface {
35 MarshalGQLContext(ctx context.Context, w io.Writer) error
36 }
37
38 type ContextUnmarshaler interface {
39 UnmarshalGQLContext(ctx context.Context, v interface{}) error
40 }
41
42 type contextMarshalerAdapter struct {
43 Context context.Context
44 ContextMarshaler
45 }
46
47 func WrapContextMarshaler(ctx context.Context, m ContextMarshaler) Marshaler {
48 return contextMarshalerAdapter{Context: ctx, ContextMarshaler: m}
49 }
50
51 func (a contextMarshalerAdapter) MarshalGQL(w io.Writer) {
52 err := a.MarshalGQLContext(a.Context, w)
53 if err != nil {
54 AddError(a.Context, err)
55 Null.MarshalGQL(w)
56 }
57 }
58
59 type WriterFunc func(writer io.Writer)
60
61 func (f WriterFunc) MarshalGQL(w io.Writer) {
62 f(w)
63 }
64
65 type ContextWriterFunc func(ctx context.Context, writer io.Writer) error
66
67 func (f ContextWriterFunc) MarshalGQLContext(ctx context.Context, w io.Writer) error {
68 return f(ctx, w)
69 }
70
71 type Array []Marshaler
72
73 func (a Array) MarshalGQL(writer io.Writer) {
74 writer.Write(openBracket)
75 for i, val := range a {
76 if i != 0 {
77 writer.Write(comma)
78 }
79 val.MarshalGQL(writer)
80 }
81 writer.Write(closeBracket)
82 }
83
84 type lit struct{ b []byte }
85
86 func (l lit) MarshalGQL(w io.Writer) {
87 w.Write(l.b)
88 }
89
90 func (l lit) MarshalGQLContext(ctx context.Context, w io.Writer) error {
91 w.Write(l.b)
92 return nil
93 }
94
View as plain text