12
votes

Is it possible run a mutation on another graphqlType from within a mutation? I'm not sure if this is a good idea or not. Ideally it would be nice to have create mutations for each one of graphql data types and then call into each of those functions when needed. Hopefully this keeps things more DRY.

For example I have 2 graphql types "projects" and "rooms". For every project a room needs to be created and the ID placed in the project for reference later.

I see 3 ways of doing this:

  • From front end, run 2 different graphql queries (for a new project and a new room) and a final one updating the project with the new room id.
  • On the backend/graphql server. Just handle all the db calls inside of one resolve function for simplicity, returning the project and the room that were created.
  • Running mutations inside a mutation. Call into the room create function from the project create function, and returning both data sets.

Still learning the ropes with graphql so any insight on whats good practice would be awesome.

2

2 Answers

5
votes

I'm sure you figured out a solution to your problem long ago, but why not just make a mutation that captures the entire process, like createProjectAndRoom? I think it's a mistake to think of GraphQL resolvers as mapping very rigidly to single actions on single models.

0
votes

The most common way to do this is on an afterInsert (or similarly-named) hook. So in this case, after the "room" has been created, create the "project" during the after insert hook.