laravel api
by Karthikeya Viswanath
通过Karthikeya Viswanath
如何在现有的Laravel应用中获取即时GraphQL API (How to get instant GraphQL APIs on your existing Laravel app)
TL; DR (TL;DR)
Setup GraphQL engine — Install Hasura GraphQL engine and expose tables over a GraphQL API
设置GraphQL引擎 —安装Hasura GraphQL引擎并通过GraphQL API公开表
In this post, we’ll use the Hasura GraphQL Engine to get instant GraphQL APIs on my existing Laravel app running locally.
在本文中,我们将使用Hasura GraphQL引擎在本地运行的现有Laravel应用上获取即时GraphQL API。
For the purpose of this project, we’ll be using a sample Laravel ToDo app built using Laravel 5.1, and modifying the code to integrate HGE. (Please note though, that Laravel 5.1 has already reached End of Life in June 2018, and you should migrate to a newer version if you’re still using this.)
就本项目而言,我们将使用一个使用Laravel 5.1构建的示例Laravel ToDo应用程序,并修改代码以集成HGE。 (不过请注意,Laravel 5.1已于2018年6月停产,如果您仍在使用它,则应迁移到新版本。)
You can find the initial sample app here, the final repository here, and a live app for you to test out here.
你可以找到初始样本应用程序在这里 ,最终的仓库在这里 ,和现场应用为你测试一下这里 。
This is what the our planned architecture will look like:
这是我们计划的体系结构的样子:
设置GraphQL引擎 (Setup GraphQL Engine)
Hasura GraphQL engine (HGE) gives you an instant realtime GraphQL API on top of your existing Postgres. HGE works out of the box with your existing:
Hasura GraphQL引擎 (HGE)在您现有的Postgres之上为您提供即时的实时GraphQL API。 HGE可与您现有的产品一起使用:
Postgres database — Connects with your existing database and provides a GraphQL API to your database.
Postgres数据库 —与现有数据库连接,并为数据库提供GraphQL API。
Authentication system — Connects with your existing authentication system to secure GraphQL API.
Migration system — Hasura GraphQL Engine doesn’t interfere with the existing Laravel migration system. Schemas can be managed separately in Laravel as long as it doesn’t alter the schema tracked by the GraphQL Engine. More info on how Hasura GraphQL engine manages your schema state here.
迁移系统 - Hasura GraphQL引擎不与现有Laravel迁移系统造成干扰。 可以在Laravel中单独管理模式,只要它不会更改GraphQL引擎跟踪的模式即可。 有关Hasura GraphQL引擎如何管理您的架构状态的更多信息,请参见此处 。
Also it comes with a nifty console, with GraphiQL integrated, which is useful while debugging GraphQL APIs.
它还带有集成了GraphiQL的漂亮控制台,在调试GraphQL API时非常有用。
安装 (Installation)
Hasura GraphQL engine can be installed on Heroku using the button below
可以使用下面的按钮将Hasura GraphQL引擎安装在Heroku上
or on any machine which can run Docker. Checkout the getting-started section for more info.
或任何可以运行Docker的机器上。 请查看入门部分以获取更多信息。
For the sake of this tutorial, we’ve set up a HGE instance for our Laravel app here (use the access-key helloworld
, we’ll explain how it works below).
为了本教程的需要,我们在这里为Laravel应用设置了一个HGE实例(使用access-key helloworld
,我们将在下面解释它的工作方式)。
使用Docker安装 (Installation using Docker)
Before installing the Hasura GraphQL Engine, you’ll need a postgres connection string. You can get this from your config/database.php
file, or your .env
file, wherever your storage credentials are kept.
在安装Hasura GraphQL Engine之前,您需要一个postgres连接字符串。 无论保存存储凭据在哪里,都可以从config/database.php
文件或.env
文件中获取此文件。
Putting the details together:
将细节放在一起:
postgres://username:SECUREPASSWORD@host:port/database_name
Follow the instructions here.
请按照此处的说明进行操作。
Once Hasura GraphQL engine starts, visiting http://localhost:8080 opens the Hasura Console. The console provides a GraphiQL instance to easily test all your GraphQL queries, mutations, and so on.
Hasura GraphQL引擎启动后,访问http:// localhost:8080将打开Hasura控制台。 该控制台提供了一个GraphiQL实例,可以轻松测试您的所有GraphQL查询,变异等。
Now go to the Data tab, and track all the tables to create instant GraphQL APIs!
现在转到“数据”选项卡,并跟踪所有表以创建即时的GraphQL API!
认证方式 (Authentication)
By default, HGE is installed in development mode. All the tables/views which are tracked by HGE can be viewed/updated without any checks. This is is not recommended for a production environment. Hasura lets you define granular access controls for every field in your GraphQL schema, that’s every table or view in your Postgres schema. These access control rules can use dynamic variables that come in with every request. Check out the docs for more information.
默认情况下,HGE以开发模式安装。 HGE跟踪的所有表/视图都可以查看/更新,而无需任何检查。 不建议在生产环境中使用此功能。 Hasura允许您为GraphQL模式中的每个字段(即Postgres模式中的每个表或视图)定义精细的访问控制。 这些访问控制规则可以使用每个请求附带的动态变量。 查看文档以获取更多信息。
HGE can be secured from direct access by configuring a webhook URL which will be called to validate every request unless the request contains a valid access-key
.
可以通过配置Webhook URL来保护HGE免于直接访问,除非请求包含有效的access-key
否则该Webhook URL将被调用以验证每个请求。
Let’s first make a simple request for users:
首先让我们向用户提出一个简单的请求:
And running it in GraphiQL:
并在GraphiQL中运行它:
Note that x-hasura-user-id
is set to “2” and x-hasura-role
is set to “user”. These are the auth
headers which will need to be set by the auth-hook
in the production mode. (GraphQL engine started with access-key
and auth-hook
).
请注意, x-hasura-user-id
设置为“ 2”, x-hasura-role
设置为“ user”。 这些是auth
标头,需要在生产模式下由auth-hook
设置。 (GraphQL引擎以access-key
和auth-hook
开头)。
安全的GraphQL API (Secure GraphQL API)
The first step is to secure HGE with anaccess-key
and configure auth-hook
with the a webhook, which in this case will be served by the Laravel app. This webhook will be invoked by the GraphQL engine, with the headers attached to the request. The webhook will return appropriate x-hasura-role
and x-hasura-user-id
, which it can obtain from authenticating the user with the Authorization
header that’s passed on from the request.
第一步是使用access-key
保护HGE并access-key
Web auth-hook
配置auth-hook
,在这种情况下,Laravel应用程序将为其提供服务。 该webhook将由GraphQL引擎调用,并将标头附加到请求中。 x-hasura-role
将返回适当的x-hasura-role
和x-hasura-user-id
,可以通过使用从请求传递过来的Authorization
标头对用户进行身份验证来获取。
Here, the auth-hook host will be your IP address on the docker bridge network if you’re using docker, or your webhook URL otherwise. You can ignore the postgres
section if you’re using an external Postgres database.
在这里,如果您使用docker,则auth-hook主机将是您在docker网桥网络上的IP地址,否则将是您的webhook URL。 如果您使用的是外部Postgres数据库,则可以忽略postgres
部分。
To set up the access-key
/ auth-hook
flags on your Heroku instance of HGE, follow these instructions. We’ll assume that the webhook is at /hge-webhook
for now, we will be setting it up on Laravel later.
要在HGE的Heroku实例上设置access-key
/ auth-hook
标志,请遵循以下说明 。 我们假设Webhook现在位于/hge-webhook
,稍后我们将在Laravel上进行设置。
Let’s try to make the query again and see what the response is.
让我们尝试再次进行查询,看看响应是什么。
This is because we haven’t configured the webhook yet, or even set the correct Authorization
headers.
这是因为我们尚未配置Webhook,甚至没有设置正确的Authorization
标头。
设置Laravel Webhook (Setting up the Laravel webhook)
Let’s set up our sample app on Heroku, so that we can easily deploy it and test out our changes.
让我们在Heroku上设置示例应用程序,以便我们可以轻松地部署它并测试我们的更改。
For the purposes of this tutorial, we’ve deployed a sample app with the webhook here. The corresponding HGE instance can be accessed here. (Access key: helloworld
)
出于本教程的目的,我们在此处使用webhook部署了一个示例应用程序。 可以在此处访问相应的HGE实例。 (访问键: helloworld
)
You can register on this sample app, and add/remove todos on the app.
您可以在此示例应用程序上注册,然后在该应用程序上添加/删除待办事项。
Let’s add a webhook now to authenticate requests sent to our HGE instance. We’ll do this using a middleware, so let’s generate a middleware class first.
现在添加一个Webhook,以验证发送到我们的HGE实例的请求。 我们将使用中间件来完成此操作,因此首先让我们生成一个中间件类。
php artisan make:middleware webhookMiddleware
php artisan make:middleware webhookMiddleware
Let’s first add the route to our app/Http/routes.php
file:
首先,将路由添加到我们的app/Http/routes.php
文件中:
Now we’ll register our middleware by adding it to the app/Http/Kernel.php
file under routeMiddleware
:
现在,我们将通过将其添加到注册我们的中间件app/Http/Kernel.php
下文件routeMiddleware
:
Now let’s set up the actual webhook at app/Http/Middleware/webhookMiddleware.php
:
现在让我们在app/Http/Middleware/webhookMiddleware.php
上设置实际的webhook:
This page simply uses the Authorization
bearer token to start a session, and then uses Laravel’s Auth to check and get the user id. You can modify this to add your custom session/token logic, and verify authentication.
该页面仅使用Authorization
承载令牌来启动会话,然后使用Laravel的Auth来检查并获取用户ID。 您可以对其进行修改以添加自定义会话/令牌逻辑,并验证身份验证。
If authenticated, we return the x-hasura-role
and x-hasura-user-id
variables as JSON. This will authenticate the request to HGE.
如果经过验证,我们将x-hasura-role
和x-hasura-user-id
变量返回为JSON。 这将向HGE验证请求。
Now, we need an easy way to get the session token of a logged in user, so let’s add this to our resources/views/users/profile.blade.php
:
现在,我们需要一种简单的方法来获取已登录用户的会话令牌,因此将其添加到我们的resources/views/users/profile.blade.php
:
Now, login in and head to the User Profile to see your new session token:
现在,登录并转到“用户个人资料”以查看新的会话令牌:
Let’s commit and deploy this to Heroku:
让我们提交并将其部署到Heroku:
git commit -am "Add HGE webhook"
git commit -am "Add HGE webhook"
git push heroku master
git push heroku master
Once it’s pushed, let’s head over to the HGE Console to test our new webhook!
推送完成后,让我们前往HGE控制台测试我们的新Webhook!
The webhook returns the corresponding x-hasura-user-id
and x-hasura-role
, and GraphQL engine responds with appropriate results as configured in the access rules.
x-hasura-user-id
返回相应的x-hasura-user-id
和x-hasura-role
,并且GraphQL引擎以访问规则中配置的适当结果进行响应。
迁移系统 (Migration System)
HGE comes with a powerful Rails-inspired migration system, and changes made in the HGE console automatically generate schema files in your folder when run as hasura console
(you can install the Hasura CLI for this).
HGE带有强大的受Rails启发的迁移系统,当以hasura console
运行时,在HGE控制台中所做的更改会自动在您的文件夹中生成架构文件(您可以为此安装Hasura CLI )。
For the purposes of this blog, though, we’ll let Laravel handle our migrations, and just export the HGE metadata so that it can track the schema and permissions separately.
不过,出于本博客的目的,我们将让Laravel处理我们的迁移,并仅导出HGE元数据,以便它可以分别跟踪架构和权限。
You can check out the HGE docs for more detailed instructions.
您可以查看HGE文档以获取更多详细说明。
Once you have everything set up as described in the above link, you can just add the folder created to your version control repository for the Laravel code.
如上述链接中所述,完成所有设置后,您只需将创建的文件夹添加到Laravel代码的版本控制存储库中即可。
To export metadata, run the following command in the folder created by the hasura init
command in the migration instructions:
要导出元数据,请在迁移说明中由hasura init
命令创建的文件夹中运行以下命令:
hasura metadata export
hasura metadata export
Since we’re letting Laravel handle the migrations, avoid making schema changes through the Hasura console, so that the Laravel migrations remain your source of truth on the schema.
由于我们让Laravel处理迁移,因此请避免通过Hasura控制台进行架构更改,以使Laravel迁移仍然是架构上真实性的来源。
That’s it! We now have a secure HGE endpoint working neatly with Laravel’s internal auth. Go forth and write code!
而已! 现在,我们有了一个安全的HGE端点,可以与Laravel的内部身份验证巧妙地协同工作。 继续写代码!
Hasura gives you instant realtime GraphQL APIs over any Postgres database without having to write any backend code.
Hasura 为您提供任何Postgres数据库上的即时实时GraphQL API,而无需编写任何后端代码。
翻译自: https://www.freecodecamp.org/news/instant-graphql-apis-on-your-existing-laravel-app-e4af9917148c/
laravel api