简体   繁体   中英

How to handle complex mutations with Rails and GraphQL

This is partly a GraphQL question, and partly a Rails application architecture question.

So lets say I'm creating a company blog, and I have 3 database models: Post, Author, and Tag. A post has_many authors and tags, and an author has_many posts. All relations are many-to-many.

I have a graphql request that looks something like this:

mutation {
  createPost(
    title: "foo"
    description:"bar"
    author: {
      name: "author1"
    }
    tags: 
      [{content: "tag1"}]
    ) {
      post {
        id
      }
      errors
    }
  }
}

And here is my mutation. This code works for the post creation, but I'm not sure how to approach the creation of the associated records.

module Mutations
    class CreatePost < Mutations::BaseMutation

        argument :title, String, required: true
        argument :description, String, required: true
        argument :author, [Types::AuthorInputType], required: false
        argument :tags, [Types::TagInputType], required: false

        field :post, Types::PostType, null: true
        field :errors, [String], null: true

        def resolve(title:, description:, author:, tags:)

            post = Post.new({title: title, description: description})

            # I want to find or create the tags and author here, and create any neccesary records and associations
            # Should that be done here? If so, how? And if not, where would this logic live instead?

            if post.save
                {
                  post: post,
                  errors: [],
                }
              else
                {
                  user: nil,
                  errors: post.errors.full_messages
                }
              end
        end
    end
end

I actually wrote about this (and more) a few months ago: A Complete Guide to Setting up a GraphQL Server on Rails .

This method of organizing code is working out well for us on our open-source project - Pupilfirst .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM