Search code examples
laravelgraphqlgraphiql

Using non-default schema in GraphQL


I'm building a GraphQL API for a mobile app backend. I'm building it on top of Laravel using rebing/graphql-laravel, and I'm having a bit of trouble.

Most of the queries and mutations require that the user be logged in, so they use authentication middleware to limit access (though at some point I plan to replace this with JWT, which is what will be used in production). However, there are two mutations that should be accessible to users who are not logged in - one to pass through the login details and get a JWT, the other to register the user and get a JWT.

The only way I could find to do this was to move these mutations to a separate auth schema. However, despite rooting through the documentation I can't for the life of me find how to specify a schema other than the default.

The mutation for creating a user looks like this:

mutation {
  createUser (
    email: "jeff@example.co.uk",
    name: "Jeff",
    password: "password"
  ) {
    token
  }
}

It works if I move the mutation to the default schema, but of course that's no use for my use case.

How do I need to adapt this to use the auth schema instead of the default schema? It sounds like it should be straightforward, but I can't for the life of me find it via Google.


Solution

  • Turns out this is straightforward enough, just seemed hard to track down.

    The URL for both the GraphQL endpoint and the GraphiQL interface has an optional parameter for the schema name field, as show in the relevant lines from the output of php artisan routes:list. This includes the following routes:

    • graphql/{default}
    • graphql/{auth}
    • graphiql/{default}
    • graphiql/{auth}

    If you navigate to the graphiql/auth in the browser, you can therefore use the queries and mutations registered to the auth schema there. Similarly, you can query graphql/auth as usual. In both cases, you'll have the middleware set for the auth schema applied.

    If you don't specify the second URL parameter, then you'll be using the default schema.