GraphQL-in-WordPress

To follow along

https://ebeldev.github.io/graphql-in-wordpress/

Let's go for a journey

How do you like to travel ?

Heavy or lightweight?

Heavy style

Lightweight style

Goals for today

  • Concepts around Api's
  • Basic knowledge of GraphQL
  • How to use it today in your developement

Étienne Bélanger

  • Self-taugh web developper
  • WordPress lover for more then 10 years
  • Work @ DistrictWeb as full-stack developer
  • Contact
    • etienne@etiennebelanger.com
    • belangeretienne
    • @ebeldev
    • @ebeldev

What is a API ? REST API ?

A api = a way for applications to talk to each other

A REST api = a api based on representational state transfer (REST) technology

REST API use HTTP Protocol to do GET, PUT, POST, DELETE operations

WordPress Rest Api

/wp-json/wp/v2

Rest Api

/wp-json/wp/v2

/posts

/media/"id"

/users/"id"

/categories/"id"

Rest Api

disadvantages

Over-fetching = a client downloads more information than is actually needed

Under-fetching = a specific endpoint doesn’t provide enough of the required information

Maintainability and Scalability having too many endpoints

Open-sourced by Facebook in 2015

A query language for your API

Advantages of GraphQL

One endpoint = /graphql

Get only the data you ask for nothing more, nothing less

It's a type language

it's self documenting docs and query autocompletion

GraphQL Basic terms

Type of operations you can do on your api

Query get your data

Mutation modify your data

Subscription subscribe to action

GraphQL has two parts

Server

Responsible for the SCHEMA of your API and resolvers of the data


					type Query {
					 posts: [Post]
					}
					
					type Post {
					 title: String
					 content: String
					 author: Author
					}
					
					type Author {
					 name: String
					 avatar: String 
					 posts: [Post]
					}
					
Client

Responsible for making the query to the server


													query {
													 posts {
													  title
													  author {
													   name
													   avatar
													  }
													 }
													}
													


					{"data": {
					  "posts": {
					   "edges": [{
					     "node": {
					      "title": "Hello World",
					      "author": {
						   name: "My super name",
					       avatar: "imgsrc.com/author.jpg"
						  }
					     }
					   }]
					  }
					}}
													

GraphQL Basic of GraphQL Query

The Query


query {
 posts {
  title
  author {
   name
   avatar
  }
 }
}

The response


								{"data": {
								  "posts": {
								   "edges": [{
								     "node": {
								      "title": "Hello World",
								      "author": {
									    name: "My super name",
								        avatar: "http://www.imgsrc.com/avatar.jpg"
									  }
								     }
								   }]  }	}}
								

GraphQL Basic of GraphQL Query

The Query with a name


query GET_POSTS {
 posts {
  title
  author {
   name
   avatar
  }
 }
}
								

The Query with arguments


query GET_POSTS {
 posts (first: 5) {
  title
  author {
   name
   avatar
  }
 }
}

The Query with variables


query GET_POSTS($first: Int){
 posts (first: $first) {
  title
  author {
   name
   avatar
  }
 }
}

// Query variables
{
"first": 5
}

GraphQL Basic of GraphQL Query

The Fragment


							fragment userFields on User {
							id
							firstName
							lastName
							phone
							username
							}
							

The Query with a fragment


query getUsers {
 admins: users(role: admin) {
  ...userFields
 }

 accountants: users(role: accountant) {
  ...userFields
 }
}
								

GraphQL Basic of GraphQL Query

The Query with a alias


					query GET_POSTS {
					 aliasname : posts {
					  title
					  author {
					   name
					   avatar
					  }
					 }
					}
								

The Query with arguments


					{
					 "data": {
					  "aliasname": {
					   "edges": [{
					    "node": {
					     "title": "Hello World",
					     "author": {
					      name: "My super name",
					      avatar: "http://www.imgsrc.com/avatar.jpg"
					     }
					    }
					   }]
					  }
					 }
					}													
					

GraphQL Basic of GraphQL Mutation


mutation {
 createPost( input:{clientMutationId: "CreatePost", title: "My new post"} ) {
  post { 
   id 
   title
   date
  }
 }
}

{ "errors": [{
 "message": "Sorry, you are not allowed to create posts",
 "category": "user",
 "locations": [	{"line": 2, "column": 3 } ],
 "path": [ "createPost" ]
}],
"data": { "createPost": null } }

GraphQL options

Server

Custom

PrismaFramework for self-hosted GraphQL server

WordExpressFramework to help develop Wordpress applications (server + client)

wp-graphqlWordPress pluginhttps://github.com/wp-graphql/wp-graphql

Client

RelayFrom Facebook, for more advance developpers

Apollo-clientApollo-boost = no setup, cache, manage local and server data

Tools to help develop

GraphiQL and Postman

WPGRAPHQL

Add custom post type to GraphQL schema


							add_action( 'init', function() {
							register_post_type( 'docs', [
							'show_in_graphql' => true,
							'hierarchical' => true,
							'graphql_single_name' => 'Document',
							'graphql_plural_name' => 'Documents',
							] );
							} );
						

WPGRAPHQL

Add custom post type you don't control to GraphQL schema


							add_filter( 'register_post_type_args', function( $args, $post_type ) {
							
							if ( 'docs' === $post_type ) {
							$args['show_in_graphql'] = true;
							$args['graphql_single_name'] = 'Document';
							$args['graphql_plural_name'] = 'Documents';
							}
							
							return $args;
							
							}, 10, 2 );
						

Extending Wp-Graphql plugin in your theme functions.php


					use WPGraphQL\Types;
					
					function wcgql_add_custom_fields_to_graphql ($fields) {
					  $fields['custom'] = [
					    'type' 			=> Types::String(),
						'description'	=> __( 'The date the film was released', 'wcmtl-graphql' ),
						'resolve'		=> function ( \WP_Post $post ) {
						  // Get your data
						  $customField = get_post_meta( $post->ID, 'custom_field_name', true );
						  // make any modification on your data
						
						  // Return your data
						  return $customField;
						},
					  ];
					
					  return $fields;
					}
					
					add_filter( 'graphql_post_fields', 'wcgql_add_custom_fields_to_graphql', 10, 1 );
					

Plugins

So how are you gonna travel now ?

REST API style

GraphQL style

Links: