lighthouse
by Oliver Nybroe
由Oliver Nybroe
Recently a new package has revolutionized the creation of a GraphQL API in Laravel. This package makes it so simple and easy to set up a GraphQL server, that it gives you the same feeling you had the first time you worked with Laravel, “What magic is this!”. This package is, of course, Lighthouse.
最近,一个新的软件包彻底改变了Laravel中GraphQL API的创建。 该软件包使设置GraphQL服务器变得如此简单和容易,以至于给您带来与您第一次使用Laravel时相同的感觉,“ 这真是太神奇了! ”。 当然,此软件包是Lighthouse 。
In this article, I will cover how to set up Lighthouse with a simple blog example. I will assume that you already are familiar with the basics of GraphQL. The example will let you get and create articles via GraphQL. Lighthouse uses a schema approach. You define your API by creating a GraphQL schema, then use directives to add bindings with Laravel.
在本文中,我将通过一个简单的博客示例介绍如何设置Lighthouse。 我假设您已经熟悉GraphQL的基础知识。 该示例将使您可以通过GraphQL获取和创建文章。 Lighthouse使用模式方法。 您可以通过创建GraphQL模式来定义API,然后使用伪指令添加与Laravel的绑定。
For getting started, simply add the package via composer and publish the config file. (The package laravel-graphql-playground
is a GraphQL browser client which is optional.)
首先,只需通过composer添加该软件包并发布配置文件。 (软件包laravel-graphql-playground
是一个GraphQL浏览器客户端,是可选的。)
$ composer require nuwave/lighthouse$ php artisan vendor:publish --provider="Nuwave\Lighthouse\Providers\LighthouseServiceProvider"$ composer require mll-lab/laravel-graphql-playground$ php artisan vendor:publish --provider="MLL\GraphQLPlayground\GraphQLPlaygroundServiceProvider"
Now for the interesting part: when setting up this package, we just have to create the following file routes/graphql/schema.graphql
. This file is the one containing our whole schema for the graphql server.
现在,对于有趣的部分:设置此程序包时,我们只需要创建以下文件routes/graphql/schema.graphql
。 该文件是包含我们针对graphql服务器的整个架构的文件。
To get started we will add a simple endpoint for getting all posts in our database. For doing this we first need to create our Article type in the schema file.
首先,我们将添加一个简单的端点来获取数据库中的所有帖子。 为此,我们首先需要在模式文件中创建Article类型。
...type Article { id: ID! title: String! body: String! author: User!}
We now have two types, a type for articles and one for users, so we can get the author of the post. However we still don’t have any endpoints for the articles, so let’s add one in the schema file.
现在,我们有两种类型,一种是文章类型,另一种是用户类型,因此我们可以获取该帖子的作者。 但是,对于这些文章,我们仍然没有任何端点,因此让我们在架构文件中添加一个端点。
type Query { ... articles: [Article]! @paginate(type: "paginator" model: "Article")}
Now some more magic is happening. We are adding a custom directive called paginate
. This directive adds pagination for the given model supplied (in this case Article). We are also saying it should use the type paginator
which will result in it making a pagination-compatible type for us.
现在,更多的魔术正在发生。 我们添加了一个名为paginate
的自定义指令。 该指令为所提供的给定模型添加分页(在本例中为Article)。 我们还说它应该使用类型paginator
,这将导致它为我们提供分页兼容的类型。
For browsing the endpoints, let’s open up the GraphQL client we installed by going to your-url.test/graphql-playground
. In the schema, we can now see that a new type called ArticlePaginator
is added. The endpoint articles
is returning an instance of the ArticlePaginator
.
要浏览端点,请转到your-url.test/graphql-playground
打开我们安装的GraphQL客户端。 在架构中,我们现在可以看到添加了一个名为ArticlePaginator
的新类型。 终结点articles
正在返回ArticlePaginator
的实例。
So let’s create a simple query to get 10 articles with their title and the name of the author.
因此,让我们创建一个简单的查询来获取10篇文章的标题和作者姓名。
query { articles(count: 10) { data { title author { name } } }}
When we run this query, it results in an error saying that it was not able to find a class called Article
. This makes sense as we haven’t created the model yet. This debug message is only visible because we are not running in a production environment.
当我们运行此查询时,将导致错误,表明无法找到名为Article
的类。 这很有意义,因为我们尚未创建模型。 仅在我们不在生产环境中运行时,此调试消息才可见。
So let’s create our models and migrations. By default, Lighthouse looks for models inside app/models
. To make it easier we will add the Article model in here. We do not have to move the User model as in the schema file, the namespace for User has been typed directly.
因此,让我们创建我们的模型和迁移。 默认情况下,Lighthouse在app/models
查找app/models
。 为了简化,我们将在此处添加Article模型。 我们不必像在模式文件中那样移动User模型,User的名称空间已直接输入。
$ php artisan make:model Models\\Article -m
Then update the migration and the models:
然后更新迁移和模型:
Now that our models and migrations are set up, let’s migrate the database and check if it still fails.
现在我们已经建立了模型和迁移,现在让我们迁移数据库并检查它是否仍然失败。
So we can see now that the endpoint works, but we have no data in the database. We will add some manually and then later tackle how to do this through GraphQL.
因此,我们现在可以看到端点可以正常工作,但是数据库中没有数据。 我们将手动添加一些内容,然后再通过GraphQL解决该问题。
Great! We are now able to fetch articles through GraphQL. Let’s also add support for getting the articles from a user instead. For doing this we have to change our GraphQL user
type to have a relationship to articles.
大! 现在,我们可以通过GraphQL获取文章。 我们还增加了对从用户那里获取文章的支持。 为此,我们必须更改GraphQL user
类型以使其与文章具有关系。
...type User { id: ID! name: String! email: String! created_at: DateTime! updated_at: DateTime! articles: [Article] @hasMany(relation:"articles" type:"paginator")}
As this is GraphQL, we could keep chaining it. So we can get the author now from the article and then the articles from that author and so on (even though that would be rather pointless).
由于这是GraphQL,我们可以继续对其进行链接。 因此,我们现在可以从该文章中找到作者,然后再从该作者那里找到文章,依此类推(即使那将毫无意义)。
Now let’s add a mutator for creating a new article. This endpoint will also need authentication. Of course, we need to be a user in the system before we can create a new article. To do this we will use Laravel’s middleware auth:api
. Remove all the previous mutations, as we do not need them, and add the following:
现在,让我们添加一个增变器以创建新文章。 该端点也将需要认证。 当然,在创建新文章之前,我们需要成为系统用户。 为此,我们将使用Laravel的中间件auth:api
。 删除所有先前的突变,因为我们不需要它们,并添加以下内容:
type Mutation @group(middleware: ["auth:api"]) { createArticle(title: String!, body: String!): Article @create(model: "Article") @inject(context: "user.id", name: "author_id")}
To use the auth:api
middleware, we will need to set up a Guard
. For this example, we will just use the TokenGuard
. For using the token guard, we need to add a field to the user called api_token
, and then the value there is your token.
要使用auth:api
中间件,我们需要设置一个Guard
。 对于此示例,我们将仅使用TokenGuard
。 为了使用令牌保护,我们需要向用户添加一个名为api_token
的字段,然后该值就是您的令牌。
Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->string('api_token'); // The new API token field $table->rememberToken(); $table->timestamps();});
Now we manually add the token in the database and set it to secret
(you can create your own UI for setting the token or use Laravel Passport). We then add this token to our request, so we are authenticated.
现在,我们在数据库中手动添加令牌并将其设置为secret
(您可以创建自己的UI来设置令牌或使用Laravel Passport )。 然后,我们将此令牌添加到我们的请求中,以便进行身份验证。
We now have a new article, and we can see that the author who made it was our authenticated user. So now we have a really simple GraphQL API up and running, but with support for getting our articles and creating them!
现在我们有一篇新文章,我们可以看到撰写该文章的作者是我们的经过身份验证的用户。 因此,现在我们已经启动并运行了一个非常简单的GraphQL API,但是支持获取和创建文章!
Hope you enjoyed this post, and if you would like to know more visit Lighthouse documentation. You can also find the example created above on Github.
希望您喜欢这篇文章,如果您想了解更多信息,请访问Lighthouse文档 。 您还可以在Github上找到上面创建的示例。
翻译自: https://www.freecodecamp.org/news/graphql-in-laravel-done-right-9cf123d5601b/
lighthouse