Metadata
Metadata attaches values of your own to a schema element: the database table
behind an object type, the cost of a field, the role an argument requires
(v0.13.0). The library stores it and gives it back, but never interprets it,
and clients cannot see it: it is not part of introspection. It is the
equivalent of extensions in graphql-js; the name differs because
Extensions already means execution hooks
here.
Use metadata instead of encoding data in names or descriptions. A description is documentation that clients read through introspection; a value hidden in it leaks to them and leaves the type undocumented.
Attaching metadata
graphql.NewMetadata takes a map and returns a graphql.Metadata, which goes
in the Metadata field of a configuration:
var bookType = graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Description: "A book in the catalogue.",
Metadata: graphql.NewMetadata(map[string]interface{}{"table": "books"}),
Fields: graphql.Fields{
"price": &graphql.Field{
Type: graphql.Float,
Metadata: graphql.NewMetadata(map[string]interface{}{"internal": true}),
},
},
})Every element of a schema accepts it:
| Element | Configuration | Read from the built schema |
|---|---|---|
| Object, interface, union, enum, input object, scalar | ObjectConfig.Metadata, InterfaceConfig.Metadata, … | Metadata() on the type |
| Field | Field.Metadata | FieldDefinition.Metadata |
| Argument | ArgumentConfig.Metadata | Argument.Metadata |
| Enum value | EnumValueConfig.Metadata | EnumValueDefinition.Metadata |
| Input object field | InputObjectFieldConfig.Metadata | InputObjectField.Metadata |
| Directive | DirectiveConfig.Metadata | Directive.Metadata |
| Schema | SchemaConfig.Metadata | Schema.Metadata() |
Fields and arguments defined through a thunk, and fields added with
AddFieldConfig, keep their metadata too.
Reading metadata
Get returns a value and whether its key is present; Keys lists the keys in
sorted order. graphql.MetadataValue returns the value already converted to
the type you ask for, and false when the key is missing or holds another
type. An element without metadata returns an empty Metadata, so reading it
never needs a nil check:
table, ok := graphql.MetadataValue[string](bookType.Metadata(), "table")
fmt.Println(table, ok) // books true
_, ok = graphql.MetadataValue[int](bookType.Metadata(), "table")
fmt.Println(ok) // false: the value is a stringIn a resolver, ResolveInfo gives the metadata of the elements involved in
the field directly:
| Call | Returns |
|---|---|
p.Info.ReturnTypeMetadata() | The metadata of the type the field returns, without its list and non-null wrappers. |
p.Info.FieldMetadata() | The metadata of the field being resolved. |
p.Info.FieldDefinition() | The field’s whole definition, including its arguments in Args with their metadata; nil when the parent type has no such field. |
p.Info.Schema.Metadata() | The schema’s metadata. |
They work out the answer from ReturnType, ParentType and FieldName, so
they also work on a ResolveInfo built outside execution.
A resolver that reads the metadata of its return type can serve many fields: the complete program below resolves every list from the table named by its element type, and refuses fields marked as internal.
Things to know
- Immutable.
NewMetadatacopies the map, so changing the map afterwards does not change the metadata, and a schema can be shared by concurrent requests. The copy is shallow: the values themselves are shared, so do not store a value that resolvers modify. - Compared by identity. Two non-empty
Metadatavalues are equal only when they come from the sameNewMetadatacall, even if their contents match. Empty values, fromNewMetadatawith a nil or empty map or the zero value, are all equal. - Server side only. Clients cannot read metadata. If a client needs a value, expose it as a field or an argument.
Complete program
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gql-go/graphql"
)
var tables = map[string][]map[string]interface{}{
"books": {{"title": "Dune", "price": 9.99}, {"title": "Emma", "price": 4.5}},
"authors": {{"name": "Frank Herbert"}, {"name": "Jane Austen"}},
}
// listResolver serves any list field whose element type names a table in its
// metadata.
func listResolver(p graphql.ResolveParams) (interface{}, error) {
table, ok := graphql.MetadataValue[string](p.Info.ReturnTypeMetadata(), "table")
if !ok {
return nil, fmt.Errorf("%s returns a type without a table", p.Info.FieldName)
}
return tables[table], nil
}
// restricted hides the value of fields marked as internal.
func restricted(p graphql.ResolveParams) (interface{}, error) {
if internal, _ := graphql.MetadataValue[bool](p.Info.FieldMetadata(), "internal"); internal {
return nil, fmt.Errorf("%s is internal", p.Info.FieldName)
}
return graphql.DefaultResolveFn(p)
}
func main() {
book := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Description: "A book in the catalogue.",
Metadata: graphql.NewMetadata(map[string]interface{}{"table": "books"}),
Fields: graphql.Fields{
"title": &graphql.Field{Type: graphql.String},
"price": &graphql.Field{
Type: graphql.Float,
Metadata: graphql.NewMetadata(map[string]interface{}{"internal": true}),
Resolve: restricted,
},
},
})
author := graphql.NewObject(graphql.ObjectConfig{
Name: "Author",
Description: "A person who wrote books in the catalogue.",
Metadata: graphql.NewMetadata(map[string]interface{}{"table": "authors"}),
Fields: graphql.Fields{"name": &graphql.Field{Type: graphql.String}},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"books": &graphql.Field{Type: graphql.NewList(book), Resolve: listResolver},
"authors": &graphql.Field{Type: graphql.NewList(author), Resolve: listResolver},
},
}),
})
if err != nil {
log.Fatal(err)
}
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: `{ authors { name } books { title price } }`,
})
out, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(out))
}authors and books share one resolver, which finds the table in the
metadata of Author and Book. price is marked as internal, so it is
refused with an error. Running the program prints:
{
"data": {
"authors": [
{ "name": "Frank Herbert" },
{ "name": "Jane Austen" }
],
"books": [
{ "price": null, "title": "Dune" },
{ "price": null, "title": "Emma" }
]
},
"errors": [
{
"message": "price is internal",
"locations": [{ "line": 1, "column": 34 }],
"path": ["books", 0, "price"]
},
{
"message": "price is internal",
"locations": [{ "line": 1, "column": 34 }],
"path": ["books", 1, "price"]
}
]
}