GraphQL
万远飞
蛋糕英语
What
Queries
type Person {
id: ID!
name: String!
age: Int!
friends: [Person]!
}
type Query {
allPersons(last: Int): [Person]!
}
query AllPersonsQuery {
allPersons {
name
}
}
{
"allPersons": [
{ "name": "Alice" },
{ "name": "Bob" },
{ "name": "Cathy" }
]
}
More on Queries
query AllPersonsQuery($first: Int!) {
allPersons(first: $first) {
name
friends {
name
}
}
}
{
"allPersons": [
{
"name": "Alice",
"friends": [
{ "name": "Bob" },
{ "name": "Cathy" }
]
}
]
}
{
"variables": {
"first": 1
}
}
Mutations
type Mutation {
createPerson(input: PersonInput!): Person
}
mutation CreatePerson ($input: PersonInput!) {
createPerson(input: $input) {
name
age
}
}
{
"allPersons": {
"name": "Alice",
"age": 36
}
}
{
"variables": {
"input": {
"name": "Alice",
"age": 36
}
}
}
Subscriptions
type Subscription {
newPerson: Person!
}
subscription {
newPerson {
name
age
}
}
{
"newPerson": {
"name": "Jane",
"age": 23
}
}
Demo
Why
How
Server (Ruby)
#Gemfile
gem 'graphql'
gem 'graphiql-rails', group: :development
#Gemfile
gem 'graphql'
gem 'graphiql-rails', group: :development
# Install
bundle
# Setup with Rails:
rails generate graphql:install
# app/graphql/types/user_type.rb
Types::UserType = GraphQL::ObjectType.define do
name "User"
field :id, !types.ID
field :name, !types.String
field :avatar, Types::PhotoType
end
# app/controllers/graphql_controller.rb
result = MySchema.execute(
params[:query],
variables: params[:variables],
context: { current_user: current_user },
)
render json: result
Show me the code!
Client (Javascript)
# npm
npm install apollo-boost react-apollo graphql-tag graphql --save
# yarn
yarn add apollo-boost react-apollo graphql-tag graphql
Q&A
GraphQL
By xpol
GraphQL
- 452