Reputation: 1515
Say I have a MemberType
like this
import {
GraphQLID,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLString
} from 'graphql'
import readPhoneNumbersByMemberId from '../resolvers/readPhoneNumbersByMemberId'
import PhoneNumberType from './PhoneNumberType'
const MemberType = new GraphQLObjectType({
name: 'Member',
fields: {
id: {
type: new GraphQLNonNull(GraphQLID)
},
firstName: {
type: new GraphQLNonNull(GraphQLString)
},
lastName: {
type: new GraphQLNonNull(GraphQLString)
},
phoneNumbers: {
type: new GraphQLList(PhoneNumberType),
resolve: readPhoneNumbersByMemberId
}
}
})
export default MemberType
and a PhoneNumberType
like this
import {
GraphQLNonNull,
GraphQLObjectType,
GraphQLString
} from 'graphql'
const PhoneNumberType = new GraphQLObjectType({
name: 'PhoneNumber',
fields: {
value: {
type: new GraphQLNonNull(GraphQLString)
}
}
})
export default PhoneNumberType
and a QueryType
like this
const QueryType = new GraphQLObjectType({
name: 'Query',
fields: {
readMembers: {
type: new GraphQLList(MemberType),
resolve: readMembers
}
}
})
Now, if I query a GraphQL schema to retrieve a member, the resolve functions readMembers
and readPhoneNumbersByMemberId
will be invoked to fetch data from a source.
Is it possible to use the same mechanism on mutations?
Upvotes: 1
Views: 300
Reputation: 1960
You can but you should not. field resolvers are really made to fetch data. Putting create/update/delete logic inside of nested resolvers could quickly become problematic and introduce the same problems you would like to solve with graphql.
It is so much discouraged to the point that facebook created a whole special type called input
for any composite objects that's sent as arguments to mutations (or query).
If you can explain the benefits of splitting the mutation logic, it might be a good RFC for GraphQL spec to accept mutate function for every field, this way you will keep the mutation logic separate while achieving the same nested nature.
If you still like to try that, you can just return an action
field on the returned object from the root resolver and make the changes you want on the nested resolvers only if you see that field. Make sure you return the data that was changed on the nested resolver.
Upvotes: 1