forked from graphql-go/relay
/
mutation.go
84 lines (74 loc) · 2.7 KB
/
mutation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package gqlrelay
import (
"github.com/chris-ramon/graphql-go/types"
)
type MutationFn func(inputMap map[string]interface{}, info types.GraphQLResolveInfo) map[string]interface{}
/*
A description of a mutation consumable by mutationWithClientMutationId
to create a GraphQLFieldConfig for that mutation.
The inputFields and outputFields should not include `clientMutationId`,
as this will be provided automatically.
An input object will be created containing the input fields, and an
object will be created containing the output fields.
mutateAndGetPayload will receive an Object with a key for each
input field, and it should return an Object with a key for each
output field. It may return synchronously, or return a Promise.
*/
type MutationConfig struct {
Name string `json:"name"`
InputFields types.InputObjectConfigFieldMap `json:"inputFields"`
OutputFields types.GraphQLFieldConfigMap `json:"outputFields"`
MutateAndGetPayload MutationFn `json:"mutateAndGetPayload"`
}
/*
Returns a GraphQLFieldConfig for the mutation described by the
provided MutationConfig.
*/
func MutationWithClientMutationId(config MutationConfig) *types.GraphQLFieldConfig {
augmentedInputFields := config.InputFields
if augmentedInputFields == nil {
augmentedInputFields = types.InputObjectConfigFieldMap{}
}
augmentedInputFields["clientMutationId"] = &types.InputObjectFieldConfig{
Type: types.NewGraphQLNonNull(types.GraphQLString),
}
augmentedOutputFields := config.OutputFields
if augmentedOutputFields == nil {
augmentedOutputFields = types.GraphQLFieldConfigMap{}
}
augmentedOutputFields["clientMutationId"] = &types.GraphQLFieldConfig{
Type: types.NewGraphQLNonNull(types.GraphQLString),
}
inputType := types.NewGraphQLInputObjectType(types.InputObjectConfig{
Name: config.Name + "Input",
Fields: augmentedInputFields,
})
outputType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
Name: config.Name + "Payload",
Fields: augmentedOutputFields,
})
return &types.GraphQLFieldConfig{
Type: outputType,
Args: types.GraphQLFieldConfigArgumentMap{
"input": &types.GraphQLArgumentConfig{
Type: types.NewGraphQLNonNull(inputType),
},
},
Resolve: func(p types.GQLFRParams) interface{} {
if config.MutateAndGetPayload == nil {
return nil
}
input := map[string]interface{}{}
if inputVal, ok := p.Args["input"]; ok {
if inputVal, ok := inputVal.(map[string]interface{}); ok {
input = inputVal
}
}
payload := config.MutateAndGetPayload(input, p.Info)
if clientMutationId, ok := input["clientMutationId"]; ok {
payload["clientMutationId"] = clientMutationId
}
return payload
},
}
}