lighthouse

by Oliver Nybroe

由Oliver Nybroe

Laravel中的GraphQL做得正确:如何在一个简单的博客中设置Lighthouse (GraphQL in Laravel done right: how to set up Lighthouse in a simple blog)

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的绑定。

分期付款 (Installment)

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"

创建模式 (Creating the schema)

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!}

定义架构查询 (Defining the schema query)

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的实例。

运行查询 (Running the query)

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的类。 这很有意义,因为我们尚未创建模型。 仅在我们不在生产环境中运行时,此调试消息才可见。

创建我们的模型和迁移 (Creating our model and migrations)

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:

然后更新迁移和模型:

查询文章 (Querying the articles)

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,我们可以继续对其进行链接。 因此,我们现在可以从该文章中找到作者,然后再从该作者那里找到文章,依此类推(即使那将毫无意义)。

创建一个变种器 (Creating a mutator)

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")}

验证增变器 (Authenticating the mutator)

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 )。 然后,我们将此令牌添加到我们的请求中,以便进行身份验证。

使用增幅器 (Using the mutator)

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

lighthouse_Laravel中的GraphQL做得正确:如何在一个简单的博客中设置Lighthouse相关推荐

  1. Keynote教程 – 将演示文稿发布到WordPress博客中

    您可以将演示文稿发布到 Medium 或 WordPress,使读者可以使用博客中的播放器点按浏览演示文稿(不包括动画效果和交互式元素).您在 Keynote 讲演中对演示文稿所做的任何更改都将自动反 ...

  2. 我从写技术博客中收获到了什么?- J_Knight_

    我是 J_Knight_,熟悉我的人都应该知道我是一名刚工作满3年的非科班 iOS 开发者,而且一直坚持写技术博客快有2年半的时间了. 其实从去年开始就一直想分享我写博客的心得,但是一直也没有找到合适 ...

  3. 在博客中加入“花絮”效果

    在博客中加入Snap Shots Snap Shots表示"花絮"的意思,在博客中可以使用Snap Shots来添加"花絮"效果. 先演示一遍效果,看是否能用: ...

  4. 做为技术人员为什么要写博客?

    做为技术人员为什么要写博客? 本文只代表个人见解,不代表任立场,如果您认为我的想法是错的那很正常,因为这是我的想法,如果您觉得您的想法和我一样,那我们就是传说中的 "激友"(对生活 ...

  5. 同步 GIT@OSC 实现MARKDOWN文件发布或更新到CSDN博客中

    还记得前面发过一篇文章,写的是关于从GITBLOG迁移博客内容到CSDN博客的文章传送门,这篇文章也是基于此写的 相信很多同学都有过这样的历程,自己辛辛苦苦写的博客,因为域名空间或等等各种原因丢失了的 ...

  6. 博客中gitalk最新评论的获取 github api使用

    博客中,对于网友的评论以及每篇文章的评论数还是很重要的.但是基于静态的页面想要存储动态的评论数据是比较难的,一般博客主题中都内置了评论插件,但是博客主题中对于最新评论的支持显示还是很少的,至少目前我是 ...

  7. 5年前我在博客中写的三目运算符的空指针问题,终于被阿里巴巴开发手册收录了。...

    △Hollis, 一个对Coding有着独特追求的人△ 这是Hollis的第 267篇原创分享 作者 l Hollis 来源 l Hollis(ID:hollischuang) 最近,阿里巴巴Java ...

  8. .net excel导入mysql_.NET Core使用NPOI将Excel中的数据批量导入到MySQL - 追逐时光者 - 博客园...

    前言: 在之前的几篇博客中写过.NET Core使用NPOI导出Word和Excel的文章,今天把同样我们日常开发中比较常用的使用Excel导入数据到MySQL数据库中的文章给安排上.与此同时还把NP ...

  9. 我来告诉你,那些博客中的gif动态图是怎么弄的?

    大家都知道,图片比单纯的文字给人的视觉冲击力更大,表达的内容也更直观易懂,经常在博客上看到动态的gif图,那这些gif动态图是怎么制作的呢,特别是Android移动开发者,写了一个demo,写博客时, ...

最新文章

  1. SpringBoot复习:4(@ImportResource)
  2. AWARD BIOS设置详解
  3. Guava库学习:学习Collections(二)Lists
  4. node和npm版本更新
  5. java 线程接口_java - 实现线程的接口
  6. dubbo源码解析(四十一)集群——Mock
  7. 这5个要点让你看清“Salesforce+AWS”
  8. 设计模式在项目中的应用案例_设计模式在项目中的应用(初学者版)
  9. php怎么检查输入名称,PHP |通过$_POST []获取输入名称
  10. echarts中triggeron与trigger不能同时出现吗_好物|痛风、血糖高、虚不受补能吃它吗?你想知道的阿胶十问十答一锅出!...
  11. vector深拷贝与浅拷贝使用总结
  12. c语言常用字符串处理函数6,【总结】C语言中常见的字符串处理函数
  13. Java服务器多站点,java客户端web服务器连接到多个web服务器
  14. TypeScript入门教程
  15. 罗技G29方向盘linux下的开发
  16. 如何制作你自己的电脑游戏
  17. 用计算机用鞋码算年龄,尺寸换算厘米对照(尺寸和厘米换算计算器)
  18. OpenBSD6.3系统安装记录
  19. JS 实现网页截屏五种方法
  20. C语言题目:数字金字塔(有条件的老师同学点一下赞呀)

热门文章

  1. IDEA中设置调整字体大小的快捷键
  2. Oracle更新sysdate,ORACLE SYSDATE 1
  3. 关于普通for循环和增强for循环
  4. Redux-Saga在React工程架构之的应用实践详解
  5. simulink 汉明码 用法_汉明码的性能分析
  6. Revit 2019 LookUp安装详解
  7. android 用swift开发,使用 Swift 语言编写 Android 应用入门
  8. 【游戏建模全流程】在Maya中制作失落城市场景
  9. 星聚宝分享几款优秀的开源博客系统
  10. PS如何将图片处理成特定像素(以标准的2寸照片为例)