[英]How to handle complex mutations with Rails and GraphQL
這部分是 GraphQL 問題,部分是 Rails 應用程序架構問題。
假設我正在創建一個公司博客,並且我有 3 個數據庫模型:Post、Author 和 Tag。 一個帖子有_many 個作者和標簽,一個作者有_many 個帖子。 所有的關系都是多對多的。
我有一個看起來像這樣的 graphql 請求:
mutation {
createPost(
title: "foo"
description:"bar"
author: {
name: "author1"
}
tags:
[{content: "tag1"}]
) {
post {
id
}
errors
}
}
}
這是我的突變。 此代碼適用於post
創建,但我不確定如何創建相關記錄。
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
幾個月前我實際上寫過這個(以及更多): 在 Rails 上設置 GraphQL 服務器的完整指南。
這種組織代碼的方法在我們的開源項目Pupilfirst中效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.