GraphQL是由Facebook開發(fā)并開源的數(shù)據(jù)查詢語言芥颈。它是一個(gè)可用于構(gòu)建強(qiáng)大API的工具。靈丹妙藥赚抡,但它絕對(duì)可以幫助你解決一些問題浇借,例如在單個(gè)請(qǐng)求中獲取許多的資源。它不會(huì)受到過度獲取或數(shù)據(jù)不足的影響怕品,并且與REST API相反,GraphQL是強(qiáng)類型的巾遭,而且沒有版本化肉康。
在本文中,我將會(huì)向你展示如何在Ruby on Rails項(xiàng)目中如何使用PostgreSQL和設(shè)置GraphQL灼舍。
建立
我假設(shè)在你的計(jì)算機(jī)上已經(jīng)安裝了最新版本的Ruby吼和。如果沒有,你可以通過asdf或rvm安裝骑素。并且已經(jīng)在你的應(yīng)用程序創(chuàng)建了一個(gè)gemset炫乓。你還需要的是安裝并運(yùn)行PostgreSQL。
通常献丑,創(chuàng)建一個(gè)新的Rails應(yīng)用程序末捣,你必須先安裝bundler
gem install bundler
然后使用此命令安裝最新的rails(可能需要一段時(shí)間)
bundle install rails
最后,使用以下命令生成一個(gè)新的rails項(xiàng)目,并指定這個(gè)項(xiàng)目所使用的數(shù)據(jù)庫创橄,我們這里選擇postgresql
rails new graphql_test --database=postgresql
創(chuàng)建一個(gè)數(shù)據(jù)庫箩做,注意創(chuàng)建數(shù)據(jù)庫前,請(qǐng)先設(shè)置你的database.yml文件
添加GraphQL
我們使用graphql-ruby gem包妥畏,所以你必須添加到你的Gemfile中邦邦。
???????
gem 'graphql'
安裝依賴
???????
bundle install
然后使用以下命令進(jìn)行安裝
rails generate graphql:install
以下是你將要做的一些事:
在config/routes.rb中添加一行路由
post "/graphql", to: "graphql#execute"
在GraphQL API中安吁,我們定義了一個(gè)可用于檢索或更改數(shù)據(jù)的端口。這個(gè)端口將在路徑/graphql中可用燃辖。但記住鬼店,你必須使用POST方法來訪問。
創(chuàng)建graphQL控制器?app / controllers / graphql_controller.rb文件黔龟,它將處理execute方法中的所有查詢:
class GraphqlController < ApplicationControllerdef executevariables = ensure_hash(params[:variables])query = params[:query]operation_name = params[:operationName]context = { # Query context goes here, for example: # current_user: current_user,}result = GraphqlTestSchema.execute(query, variables: variables,context: context,operation_name: operation_name)render json: resultrescue => eraise e unless Rails.env.development?handle_error_in_development eend # private methods are also here but are not relevant for nowend
需要注意的是我們收集GraphqlTestSchema.execute方法的參數(shù)的方式妇智。
添加了很多base類型:
???????
base_enum, base_input_object, base_interface, base_object, base_scalar, base_union, mutation_type, query_type
我們將使用它們來構(gòu)建mutations,查詢捌锭,接口和其他類型俘陷。
將gem“graphiql-rails”,group :: development添加到你的Gemfile中观谦,該Gemfile安裝了在開發(fā)期間使用的GraphiQL IDE拉盾。最后記住bundle install。查看routes.rb文件豁状,會(huì)生成以下代碼行:
if Rails.env.development? mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"end
這樣就能夠使用/ graphiql路徑在本地進(jìn)行測(cè)試捉偏。
添加app / graphql / store_manager_schema.rb,它將成為整個(gè)應(yīng)用程序的入口
class GraphqlTestSchema < GraphQL::Schema? mutation(Types::MutationType)? query(Types::QueryType)end
創(chuàng)建模型和數(shù)據(jù)
???????rails generate model Author first_name:string last_name:string date_of_birth:date --no-test-frameworkrails generate model Book title:string author:references publication_date:integer genre:string --no-test-framework
它們將生成我們可以使用rake db:migrate運(yùn)行的遷移泻红。他們還將生成模型夭禽。我們唯一要做的就是添加
has_many :books
到app / models / author.rb中
編輯db / seeds.rb:
stephen = Author.create(first_name: 'Stephen', last_name: 'King', date_of_birth: Date.parse('1947-09-21'))lee = Author.create(first_name: 'Lee', last_name: 'Child', date_of_birth: Date.parse('1954-10-29'))
Book.create(title: 'The Shining', author: stephen, publication_date: 1977, genre: 'Horror')Book.create(title: 'Carrie', author: stephen, publication_date: 1974, genre: 'Horror')Book.create(title: 'It', author: stephen, publication_date: 1986, genre: 'Horror')Book.create(title: 'Green mile', author: stephen, publication_date: 1996, genre: 'Mystery')Book.create(title: 'Killing Floor', author: lee, publication_date: 1997, genre: 'Thriller')Book.create(title: 'Die Trying', author: lee, publication_date: 1998, genre: 'Thriller')
使用rake db:seed運(yùn)行seeds
生成類型
正如我之前提到的,GraphQL是強(qiáng)類型的谊路,這意味著如果我們想要查詢Author和Book讹躯,我們必須為它們定義類型。
app/graphql/types/author_type.rb
module Typesclass AuthorType < Types::BaseObject? ? field :books, [Types::BookType], null: true? ? field :id, ID, null: false? ? field :date_of_birth, String, null: false? ? field :first_name, String, null: false? ? field :last_name, String, null: falseend
app/graphql/types/book_type.rb
module Typesclass BookType < Types::BaseObject field :author, Types::AuthorType, null: false field :genre, Enums::Genre, null: false
field :id, ID, null: false
field :publication_date, Integer, null: false field :title, String, null: falseendend
我們有一個(gè)約定缠劝,我們?cè)陧敳刻砑觕omplex類型潮梯,然后是ID,最后是simple類型惨恭,如Integer秉馏,String等。正如你看到的脱羡,我們正在使用類型的枚舉萝究。 我們?cè)趩为?dú)的目錄app / graphql / types / enums / genre.rb中定義枚舉。
閱讀全文
https://mp.weixin.qq.com/s?__biz=MzU2MTY0NDY4Ng==&tempkey=MTAwM19GT3lWRnA4U1grckJsbTN2MlVaV2pnQzdBbVNDNktGUlBuMnF6N19ZWTVNOVpsTkQydWJRdlJNWm4wSmZxUkNCLWdXcXhmdTh3a05yYUJaZE5iR1p2b3J5di0wckpUQTRvOEp4dzhGVi1XSWdBbmp1aTlCQmJTS28yaW1rVmFxUnBZSW9HVUM3V0xXRER0TVdINmVwaWRCQ0VfeTE1dno1R3NPWEtnfn4%3D&chksm=7c74d4cf4b035dd95dae327f8664e475d82e88c91d54dc56c75ff6c23c72b9164799f6c0772f#rd
微信公眾號(hào):