WordPressなしでGato GraphQLを実行する
Gato GraphQLは、Composerで管理されたスタンドアロンのPHPコンポーネントを使って構築されており、GraphQLサーバーを構成するすべてのPHPコンポーネントがWordPressに依存しないように設計されています。
そのため、GraphQLサーバーはスタンドアロンのPHPアプリケーションとして実行でき、WordPressベースのアプリケーションやそれ以外の任意のPHPアプリケーションに組み込むことができます。
特定のユースケースでアプリケーションがWordPressのデータにアクセスする必要がない場合、少なくともそのユースケースでは、すぐに利用を開始できます。
このビデオは、そのようなユースケースを実演しています。GitHubのAPIと連携し、開発中にGitHub Actionsからアーティファクトをダウンロード・インストールする例です:
このビデオでは、GraphQLクエリがHTTPリクエストを実行し、GitHub Actionsで生成された最新のGato GraphQLプラグインを取得します。これらはプルリクエストのマージ時にアーティファクトとしてアップロードされます。
GraphQLレスポンスから得たアーティファクトのURLは、WP-CLIに注入され、ローカルのDEV Webサーバーにプラグインを自動的にインストールしてテストを実行します。
このユースケースでは、WordPressのデータに一切アクセスしないため、GraphQLサーバーはすでにスタンドアロンのPHPアプリとして実行できます。
詳細:Gato GraphQLをスタンドアロンPHPアプリとして実行する
ここでは、デモビデオの詳細な説明を行います。
実行するGraphQLクエリは、ファイル retrieve-github-artifacts.gql に記述します。
このクエリは、環境変数 GITHUB_ACCESS_TOKEN からアクセストークンを取得してGitHub APIに接続します。提供された変数から actions/artifacts エンドポイントのフルパスを動的に生成し、それに対してHTTPリクエストを送信します。
レスポンスから、各アーティファクトアイテム内の「ダウンロードURL」を抽出し、それらに対して非同期HTTPリクエストを送信します。各「ダウンロードURL」の Location ヘッダーから、ダウンロード可能なファイルの実際のURLを取得します。
最後に、WP-CLIへの注入を便利にするために、すべてのURLをスペース区切りでまとめて出力します。
# File retrieve-github-artifacts.gql
query RetrieveProxyArtifactDownloadURLs(
$repoOwner: String!
$repoProject: String!
$perPage: Int = 1
$artifactName: String = ""
) {
githubAccessToken: _env(name: "GITHUB_ACCESS_TOKEN")
@remove
# Create the authorization header to send to GitHub
authorizationHeader: _sprintf(
string: "Bearer %s"
values: [$__githubAccessToken]
)
@remove
# Create the authorization header to send to GitHub
githubRequestHeaders: _echo(
value: [
{ name: "Accept", value: "application/vnd.github+json" }
{ name: "Authorization", value: $__authorizationHeader }
]
)
@remove
@export(as: "githubRequestHeaders")
githubAPIEndpoint: _sprintf(
string: "https://api.github.com/repos/%s/%s/actions/artifacts?per_page=%s&name=%s"
values: [$repoOwner, $repoProject, $perPage, $artifactName]
)
# Use the field from "Send HTTP Request Fields" to connect to GitHub
gitHubArtifactData: _sendJSONObjectItemHTTPRequest(
input: {
url: $__githubAPIEndpoint
options: { headers: $__githubRequestHeaders }
}
)
@remove
# Finally just extract the URL from within each "artifacts" item
gitHubProxyArtifactDownloadURLs: _objectProperty(
object: $__gitHubArtifactData
by: { key: "artifacts" }
)
@underEachArrayItem(passValueOnwardsAs: "artifactItem")
@applyField(
name: "_objectProperty"
arguments: { object: $artifactItem, by: { key: "archive_download_url" } }
setResultInResponse: true
)
@export(as: "gitHubProxyArtifactDownloadURLs")
}
query CreateHTTPRequestInputs
@depends(on: "RetrieveProxyArtifactDownloadURLs")
{
httpRequestInputs: _echo(value: $gitHubProxyArtifactDownloadURLs)
@underEachArrayItem(passValueOnwardsAs: "url")
@applyField(
name: "_objectAddEntry"
arguments: {
object: {
options: { headers: $githubRequestHeaders, allowRedirects: null }
}
key: "url"
value: $url
}
setResultInResponse: true
)
@export(as: "httpRequestInputs")
@remove
}
query RetrieveActualArtifactDownloadURLs
@depends(on: "CreateHTTPRequestInputs")
{
_sendHTTPRequests(inputs: $httpRequestInputs) {
artifactDownloadURL: header(name: "Location")
@export(as: "artifactDownloadURLs", type: LIST)
}
}
query PrintSpaceSeparatedArtifactDownloadURLs
@depends(on: "RetrieveActualArtifactDownloadURLs")
{
spaceSeparatedArtifactDownloadURLs: _arrayJoin(
array: $artifactDownloadURLs
separator: " "
)
}PHPのロジックは、Gato GraphQLプラグインと「Power Extensions」バンドル(HTTPリクエストの送信やその他の機能に必要)のコードを直接ロードします。
スタンドアロンのPHPアプリとして、どのモジュールを初期化するかを明示的に指定し、デフォルト以外の設定を提供する必要があります。
たとえば、モジュール SendHTTPRequests に対して https://api.github.com/repos への接続を許可し、モジュール EnvironmentFields に対して環境変数 GITHUB_ACCESS_TOKEN へのアクセスを許可するように設定します。
GraphQLスキーマはGraphQLクエリが最初に実行されたときに生成され、ディスクにキャッシュされることに注意してください。これにより、2回目以降はスキーマを計算するためのコードが一切実行されず、実行が高速化されます。
最後に、スタンドアロンアプリがGraphQLサーバーを初期化し、クエリを実行し、レスポンスを出力します。
<?php
// File retrieve-github-artifacts.php
declare(strict_types=1);
use GraphQLByPoP\GraphQLServer\Server\StandaloneGraphQLServer;
use PoP\Root\Container\ContainerCacheConfiguration;
// Load the GraphQL server via the standalone PHP components
require_once (__DIR__ . '/wordpress/wp-content/plugins/gatographql/vendor/scoper-autoload.php');
// Load the PRO extensions via the standalone PHP components
require_once (__DIR__ . '/wordpress/wp-content/plugins/gatographql-power-extensions-bundle/vendor/scoper-autoload.php');
// Modules required in the GraphQL query
$moduleClasses = [
\PoPSchema\EnvironmentFields\Module::class,
\PoPSchema\FunctionFields\Module::class,
\GraphQLByPoP\ExportDirective\Module::class,
\GraphQLByPoP\DependsOnOperationsDirective\Module::class,
\GraphQLByPoP\RemoveDirective\Module::class,
\PoPSchema\ApplyFieldDirective\Module::class,
\PoPSchema\SendHTTPRequests\Module::class,
\PoPSchema\ConditionalMetaDirectives\Module::class,
\PoPSchema\DataIterationMetaDirectives\Module::class,
];
// Configure the modules
$moduleClassConfiguration = [
\PoP\GraphQLParser\Module::class => [
\PoP\GraphQLParser\Environment::ENABLE_MULTIPLE_QUERY_EXECUTION => true,
\PoP\GraphQLParser\Environment::USE_LAST_OPERATION_IN_DOCUMENT_FOR_MULTIPLE_QUERY_EXECUTION_WHEN_OPERATION_NAME_NOT_PROVIDED => true,
\PoP\GraphQLParser\Environment::ENABLE_RESOLVED_FIELD_VARIABLE_REFERENCES => true,
\PoP\GraphQLParser\Environment::ENABLE_COMPOSABLE_DIRECTIVES => true,
],
\PoPSchema\SendHTTPRequests\Module::class => [
\PoPSchema\SendHTTPRequests\Environment::SEND_HTTP_REQUEST_URL_ENTRIES => [
'#https://api.github.com/repos/(.*)#',
],
],
\PoPSchema\EnvironmentFields\Module::class => [
\PoPSchema\EnvironmentFields\Environment::ENVIRONMENT_VARIABLE_OR_PHP_CONSTANT_ENTRIES => [
'GITHUB_ACCESS_TOKEN',
],
],
];
// Cache the schema to disk, to speed-up execution from the 2nd time onwards
$containerCacheConfiguration = new ContainerCacheConfiguration('MyGraphQLServer', true, 'retrieve-github-artifacts', __DIR__ . '/tmp');
// Initialize the server
$graphQLServer = new StandaloneGraphQLServer($moduleClasses, $moduleClassConfiguration, [], [], $containerCacheConfiguration);
/**
* GraphQL query to execute, stored in its own .gql file
*
* @var string
*/
$query = file_get_contents(__DIR__ . '/retrieve-github-artifacts.gql');
// GraphQL variables
$variables = [
'repoOwner' => 'GatoGraphQL',
'repoProject' => 'GatoGraphQL',
'perPage' => 3
];
// Execute the query
$response = $graphQLServer->execute(
$query,
$variables,
);
// Print the response
echo $response->getContent();GraphQLクエリを実行するには、ターミナルで次のコマンドを実行します(jq を使用してJSONを整形表示):
php retrieve-github-artifacts.php | jq最後に、GraphQLレスポンスからアーティファクトのURLを抽出してWP-CLIに注入するには、次のコマンドを実行します:
GITHUB_ARTIFACT_URLS=$(php retrieve-github-artifacts.php \
| grep -E -o '"spaceSeparatedArtifactDownloadURLs\":"(.*)"' \
| cut -d':' -f2- | cut -d'"' -f2- | rev | cut -d'"' -f2- | rev \
| sed 's/\\\//\//g')
wp plugin install ${GITHUB_ARTIFACT_URLS} --force --activate