Lesson 2: Querying dynamic data
Gato GraphQL can further augment WordPress' capabilities to search data via the use of "function" fields (a distinct type of field which provides functionality instead of data), allowing us to dynamically compute data, input it back into the query, and affect the response with granular control.
Examples
Gato GraphQL provides function fields under the concept of Global fields: Fields that are accessible under all the types from the GraphQL schema. (Normal fields in GraphQL, in contrast, are accessible only under some specific type, such as Post
or User
).
By convention, global fields in Gato GraphQL start with _
(and normal fields do not).
The PHP Functions Via Schema extension provides many of the most common PHP functions as global fields, including:
_arrayItem
_arrayJoin
_date
_equals
_inArray
_intAdd
_isEmpty
_isNull
_makeTime
_objectProperty
_sprintf
_strContains
_strRegexReplace
_strSubstr
_time
,- And many more...
We can create dynamically-generated data, and input it into a filter to fetch posts, comments, etc.
This query retrieves the number of comments added to the site in the last 24 hs, which is computed as "time now minus 86400 seconds":
$__timeNow
is a variable dynamically created by the Field to Input extension, which allows us to obtain the value of a field and input it into another field in that same operation.
The field to obtain the value from is referenced using the "Variable" syntax $
, and __
before the field alias or name:
This query retrieves the number of comments added to the site starting from "24 hours ago", "1 year ago", "beginning of the month", and "beginning of the year":
This query is the same as the previous one, however it retrieves the standardized time format "Y-m-d\\TH:i:sO"
from PHP constant DATE_ISO8601
:
Field _env
is provided via the PHP Constants and Environment Variables via Schema extension.
Via the applied Schema Configuration and plugin Settings, we can configure which constants and environment variables can be queried.