将来自 Shopify API 的 GraphQL 查询保存在 postgres 数据库中

Save GraphQL query from Shopify API in postgres databsae

问题: 如何将 GraphQL 查询保存到我的 local/postgres 数据库?

(假设我只想保存一两个字段——我会做更多,但我只是不确定如何开始。)

背景:

型号

shop.rb

class Shop < ActiveRecord::Base
  include ShopifyApp::ShopSessionStorage
  has_many :orders

  def api_version
    ShopifyApp.configuration.api_version
  end

  session = ShopifyAPI::Session.new(domain: "bryanbeshore.myshopify.com", token: Shop.first.shopify_token, api_version: "2020-04")
  ShopifyAPI::Base.activate_session(session)

  client = ShopifyAPI::GraphQL.client

  SHOP_NAME_QUERY = client.parse <<-'GRAPHQL'
      {
    shop {
      name
    }
    orders(first: 100) {
      edges {
        node {
          id
          name
          createdAt
          shippingAddress {
            address1
            address2
            city
            province
            provinceCode
            zip
          }
        }
      }
    }
    }
  GRAPHQL
end

控制器

home_controller.rb

class HomeController < AuthenticatedController

  def index
    client = ShopifyAPI::GraphQL.client
    @shop_orders = client.query(Shop::SHOP_NAME_QUERY).data.to_json
  end
end

查看

app/views/home/index.html.erb

<p><%= @shop_orders %></p>

当前架构

ActiveRecord::Schema.define(version: 2020_05_06_181457) do

  create_table "orders", force: :cascade do |t|
    t.string "shopify_order_id", null: false
    t.string "shopify_order_name", default: ""
    t.datetime "shopify_order_created_at"
    t.integer "shop_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["shop_id"], name: "index_orders_on_shop_id"
    t.index ["shopify_order_id"], name: "index_orders_on_shopify_order_id", unique: true
  end

  create_table "shops", force: :cascade do |t|
    t.string "shopify_domain", null: false
    t.string "shopify_token", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["shopify_domain"], name: "index_shops_on_shopify_domain", unique: true
  end

end

您正在查询 Shop 个订单,所以我会创建一个 Order 模型/orders table,确保它属于一家商店。

  • rails g model Order payload:jsonb shop:references,对于这个例子,我只是创建一个 jsonb 字段,我们将把整个 JSON 对象转储到其中。
  • rails db:migrate
  • models/order.rb
  • 中添加belongs_to :shop
  • 确保 Shop 型号有此 has_many :orders,通常 rails 为您添加

现在,当您从 Shopify 获取 JSON 负载时,循环遍历它并为您收到的每个订单创建一个新记录。

所以在你用来查询订单的方法中添加这个。

shopify_json_response.each do |item|
  orders.create(payload: item)
end

或多或少,这应该可以解决问题。 您不需要后台作业,但是当您想要处理不需要立即处理的数据时,后台作业是理想的选择。