Querying GraphQL

Okay, now for the moment of truth! Let's start querying our GraphQL server and exploring the data.

GraphiQL

To query our GraphQL server, we're going to use an Electron app called GraphiQL which you can download here. Next, just follow the directions to start up the server and querying our data.

Start Up the PHP Server

$ php artisan serve

Our server should now be running on http://localhost:8000. Lighthouse automatically sets up a /graphql endpoint to send GraphQL queries, so set the GraphiQL Endpoint in GraphiQL to http://localhost:8000/graphqland add the following query

{
  viewer {
    name
    email
  }
}

When you hit the "Play" (or Ctrl-Enter on a Mac) button, you should get the following output

Auth Middleware

I know, not too exciting yet, but trust me we'll get there! Okay, so we sent a request to our ViewerQuery but got back null. That's because the ViewerQuery returns the authenticated user and we haven't logged in. So let's mock out that functionality for the time being so we can get going a bit quicker.

Create Middleware

$ php artisan make:middleware MockLogin

Middleware Class

We're just going to auto-login the first user in our database. Obviously do not do this in your application, it is simply there so we don't have to manually log in and store a cookie or set a authorization header.

// app/Http/Middleware/MockLogin.php

namespace App\Http\Middleware;

use Closure;

class MockLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // DON'T DO THIS IN A REAL APP
        if (!auth()->check() && env('APP_ENV') !== 'production') {
            auth()->setUser(\App\User::first());
        }

        return $next($request);
    }
}

Register Middleware

Now we just need to register our middleware in our http kernel.

// app/Http/Kernel.php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // ...
        \App\Http\Middleware\MockLogin::class,
    ];

    // ...
}

Re-run Query

Okay, now that we will automatically be logged in with the first user in our DB, let's re-run the query in GraphiQL.

Be sure your server is still running

Awesome! We're now getting the authenticated user sent back to us in our query. But, this obviously doesn't do GraphQL any justice. We need to add some relationships to our UserType so we can dig deeper into our queries.

results matching ""

    No results matching ""