vapor 后端开发_如何使用Vapor 4和Swift构建待办事项列表后端

vapor 后端开发

前言 (Preamble)

Todo-Backend is a great project that provides a simple web API spec for managing a to-do list. You can implement the API yourself and provide an endpoint to learn more about the server framework of your choice (in this article we’re going to use ServerSideSwift with Vapor 4).Once you have it set up you can add the test target URL here, run tests and implement your API until you satisfy all tests. It’s a great learning opportunity!

Todo-Backend是一个很棒的项目,它提供了用于管理待办事项列表的简单Web API规范。 您可以自己实现API并提供一个端点,以了解有关您选择的服务器框架的更多信息(在本文中,我们将使用ServerSideSwift与Vapor 4一起使用)。设置完成后,您可以在此处添加测试目标URL ,运行测试并实施您的API,直到满足所有测试为止。 这是一个很好的学习机会!

Add your server here and run the tests to get feedback 在此处添加服务器并运行测试以获取反馈

In this tutorial you will learn:

在本教程中,您将学习:

  • How to use Todo-Backend and satisfy its spec using TDD

    如何使用Todo-Backend并使用TDD满足其规格

  • How to make your local backend available using ngrok

    如何使用ngrok使本地后端可用

  • How to configure CORS

    如何配置CORS

  • How to write routes

    如何写路线
  • How to CRUD to-dos

    如何进行待办事项
  • How to work with model migrations

    如何处理模型迁移

设置项目 (Setting up the Project)

创建蒸气项目 (Creating the Vapor project)

There are just a few steps required to get a fully running Vapor backend on your machine.

仅需几个步骤,即可在计算机上获得完全运行的Vapor后端。

Clone the Vapor api-template (branch: 4) into a folder of your choice:

Vapor api-template (分支:4)克隆到您选择的文件夹中:

$ git clone https://github.com/vapor/api-template.git -b 4 todo-backend-vapor

Note: currently the Vapor 4 template is in a branch called 4. If you read this article later it may already be merged into master. If so, just remove -b 4 from the above command.

注意: 当前Vapor 4模板位于名为 4 的分支中 如果您稍后阅读本文,则可能已经合并到母版中。 如果是这样,只需 从上述命令中 删除 -b 4

Open the project in Xcode:

在Xcode中打开项目:

  • Drag and drop the folder or Package.swift into the Xcode app icon

    文件夹或Package.swift 拖放到Xcode应用程序图标中

Or:

要么:

  • Via terminal, change the directory to your new project (in my case: todo-backend-vapor) and type open Package.swift.

    通过终端,将目录更改为新项目(在我的情况下为todo-backend-vapor ),然后键入open Package.swift

在Xcode中添加工作目录 (Add a working directory in Xcode)

Edit your Run scheme and enable “Use custom working directory”. Set it to the root of your project. This is required when running in Xcode to ensure our SQLite database file is stored there.

编辑您的Run方案并启用“使用自定义工作目录”。 将其设置为项目的根目录。 在Xcode中运行时,这是必需的,以确保我们SQLite数据库文件存储在此处。

Add custom working directory 添加自定义工作目录

启用自动迁移 (Enable auto migrations)

Now let’s add one more step to enable auto-migration. Vapor’s ORM Fluent will try to migrate your models/schemes on startup:

现在,让我们再添加一个步骤来启用自动迁移。 Vapor的ORM Fluent将在启动时尝试迁移您的模型/方案:

Enable automatic migration 启用自动迁移

Wait until all packages are resolved, select the Run scheme and run your project:

等到所有软件包都解决后,选择Run方案 并运行您的项目:

Running the Vapor API template 运行蒸气API模板

You’ll notice that db.sqlite has been created. Feel free to inspect it with a database client of your choice, such as TablePlus or SQLiteStudio.

您会注意到db.sqlite已创建。 随时使用您选择的数据库客户端(例如TablePlus或SQLiteStudio)对其进行检查 。

Switch to your browser and open http://localhost:8080. You should see that it’s working!

切换到浏览器并打开http:// localhost:8080 。 您应该看到它正在运行!

设置ngrok (Setting up ngrok)

To make your local back end visible and available to todobackend.com, we’re going to use ngrok.

为了使您的本地后端可见并可以用于todobackend.com,我们将使用ngrok

One time setup actions:

一次设置操作:

  • Go to https://ngrok.com/download

    转到https://ngrok.com/download

  • Download the client, unzip and save it somewhere. e.g. in /Applications

    下载客户端,解压缩并将其保存在某处。 例如在/Applications

  • Create a free account with ngrok

    使用ngrok创建一个免费帐户
  • Find your auth token here: https://dashboard.ngrok.com/get-started/setup

    在此处找到您的身份验证令牌: https : //dashboard.ngrok.com/get-started/setup

  • Connect your account, in the terminal type:

    在终端类型中连接您的帐户:
$ /Applications/ngrok authtoken {your auth token}

启动ngrok (Start ngrok)

  • From now on, whenever you want to create a tunnel to your local backend, you can just type:

    从现在开始,每当您要创建到本地后端的隧道时,只需键入:
$ /Applications/ngrok http 8080

This will make your local port 8080 reachable via the URL provided by ngrok:

这将通过ngrok提供的URL使本地端口8080可以访问:

Note: in a free account the URL changes whenever you stop/start ngrok. But this shouldn’t bother us now.

注意: 在免费帐户中,无论何时停止/启动ngrok,URL都会更改。 但这现在不应该困扰我们。

Copy the HTTPS URL to your browser. You should see that it works again. Great, your back end is now reachable from outside!

将HTTPS URL复制到浏览器。 您应该看到它再次起作用。 太好了,您现在可以从外面到达后端了!

Note: ngrok provides a great web interface where you can track incoming requests. This is very useful for debugging — you can open it by navigating to http://127.0.0.01:4040 in your browser.

注意: ngrok 提供了一个出色的Web界面,您可以在其中 跟踪传入的请求 这对于调试非常有用-您可以通过 在浏览器中 导航到 http://127.0.0.01:4040 来打开它

将您的后端连接到Todo-Backend (Connecting your backend to Todo-Backend)

Next you’ll connect you backend to Todo-Backend. Make sure your backend in Xcode is still running.

接下来,将后端连接到Todo-Backend。 确保您的Xcode后端仍在运行。

  • Go to https://todobackend.com/specs/

    转到https://todobackend.com/specs/

  • Add your https URL and append /todos e.g. https://e03cfeab1b7d.ngrok.io/todos

    添加您的https URL并附加/todos例如https://e03cfeab1b7d.ngrok.io/todos

Note: the /todos endpoint is already provided for you in the vapor api-template project.

注意: 蒸气 api-template 项目中 已经为您提供 /todos 端点

  • Run the tests:

    运行测试:
Test results from Todo-Backend 来自Todo-Backend的测试结果

Great! It was able to access our server but all tests are failing. Now it’s time to satisfy the spec.

大! 它能够访问我们的服务器,但所有测试均失败。 现在该满足规格了。

实施您的Todo-后端API (Implementing Your Todo-Backend API)

修复CORS (Fixing CORS)

CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

CORS是一种机制,它使用附加的HTTP标头来告诉浏览器,使运行在一个来源的Web应用程序可以访问来自另一个来源的选定资源。 Web应用程序请求其来源(域,协议或端口)不同的资源时,将执行跨域HTTP请求。

If you want to learn more about CORS, checkout this article by Mozilla.

如果您想了解有关CORS的更多信息,请查看 Mozilla的这篇文章

In Vapor you can enable CORS by adding the CORSMiddleware. In routes.swift update the middlewares and add CORS with the default configuration:

在Vapor中,您可以通过添加CORSMiddleware来启用CORS。 在routes.swift更新中间件并使用默认配置添加CORS:

Line 5: Add CORSMiddleware 第5行:添加CORSMiddleware

If you refresh the Todo-Backend tests page, the first two tests should now pass:

如果刷新“待办事项后端测试”页面,则前两个测试现在应该通过:

Test results from Todo-Backend 来自Todo-Backend的测试结果

As you can see, we not only satisfied the CORS requirements but also the POST /todos test. Vapor’s api-template has already implemented this. You can find the endpoint in routes.swift and the implementation in TodoController.swift.

如您所见,我们不仅满足CORS要求,还满足POST /todos测试。 Vapor的api模板已经实现了此功能。 您可以在端点routes.swift并在实施TodoController.swift

实施“全部删除” (Implementing “delete all”)

Todo-Backend expects a delete all todos endpoint under DELETE /todos. To implement this, switch to TodoController.swift and add a new route handler:

Todo-Backend希望delete all todos DELETE /todos下的delete all todos端点。 要实现此目的,请切换到TodoController.swift并添加一个新的路由处理程序:

Now switch to routes.swift and add the DELETE /todos endpoint to the end:

现在切换到routes.swift ,并将DELETE /todos端点添加到末尾:

Run your app and refresh the Todo-Backend Tests:

运行您的应用并刷新待办事项后端测试:

Great — we’re already passing five tests!

太好了-我们已经通过了五项测试!

修复TODO模型 (Fix the TODO model)

As outlined in the test output, Todo-Backend expects our Todo model to have a field completed. Let’s update our Todo model:

如测试输出中所述,Todo-Backend希望我们的Todo模型具有一个completed的字段。 让我们更新我们的Todo模型:

Add a new field `completed` to our `Todo` model 在我们的`Todo`模型中添加一个新的`completed`字段

// 1.) Add a new field with the name completed of type Bool.

// 1.)添加一个新的字段名称completed类型的Bool

// 2.) Update the initializer with a default value of false for completed.

// 2.)用default的false值更新initializer来completed

Now you have to update the scheme. Go to CreateTodo.swift and add the completed field:

现在,您必须更新方案。 转到CreateTodo.swift并添加completed字段:

Add a new field `completed` to our Todo migration 在我们的Todo迁移中添加一个新字段“ completed”

Now delete the db.sqlite file and run your project again.

现在,删除db.sqlite文件,然后再次运行您的项目。

Note: in a production environment you want to avoid deleting the database. In this case, you can also modify your migrations. Take a look here for more details.

注意: 在生产环境中,您要避免删除数据库。 在这种情况下,您也可以修改迁移。 看看 这里 了解更多详情。

Once your project is running, reload the Todo-Backend tests. You’ll notice that more tests are failing now and errors are piling up in your console. For example the previously passing /POST todos test is failing. This is due to our new completed field, which we made required but is not provided by Todo-Backend when creating a new todo.

项目运行后,重新加载Todo-Backend测试。 您会注意到,现在有更多测试失败,并且控制台中堆积了很多错误。 例如,先前通过的/POST todos测试失败。 这是因为我们的新completed领域,我们做了要求 ,但创建一个新的待办事项时不被藤,后端提供。

Let’s update our TodoController to work with specific models for creating a Todo. Switch to TodoController.swift, add a new CreateTodoRequestBody struct, and update create(req:):

让我们更新TodoController使其与用于创建Todo的特定模型一起使用。 切换到TodoController.swift ,添加一个新的CreateTodoRequestBody结构,并更新create(req:)

Note: if you are new to Vapor and want to understand its asynchronicity and when to use map , flatMap or flatMapThrowing checkout the Vapor 4 async docs.

注意: 如果您是Vapor的新手,并且想了解它的 异步性 以及何时使用 map flatMap flatMapThrowing 签出 Vapor 4 异步 文档

Re-run the project and the Todo-Backend tests. We have already six passing tests:

重新运行项目和Todo-Backend测试。 我们已经有六个通过测试:

6 passed, 10 failing — way to go 通过6次,失败10次-way

添加自定义Todo API模型 (Add a custom Todo API model)

Todo-Backend expects all returned Todo objects to contain a property url with a link to their resource. In a RESTful API this should be /todos/{resource identifier}, where {resource identifier} is the id of our Todo.

Todo-Backend希望所有返回的Todo对象都包含一个属性url并带有指向其资源的链接。 在RESTful API中,它应该是/todos/{resource identifier} ,其中{resource identifier}是我们Todoid

As it doesn’t make sense to add a URL to the database (this would be adding redundant information and the URL might change based on environments) we’ll introduce a new API model for our Todo entity. In the Models folder create a new file TodoAPIModel.swift:

由于向数据库添加URL没有意义(这将添加冗余信息,并且URL可能会根据环境而变化),因此我们将为Todo实体引入一个新的API模型。 在Models文件夹中,创建一个新文件TodoAPIModel.swift

Our `TodoAPIModel` 我们的`TodoAPIModel`

You’re creating a new model with the required url property and a convenience initializer to easily init our new model with a Todo.

您正在使用所需的url属性和便捷的初始化程序创建一个新模型,以使用Todo轻松初始化我们的新模型。

Now you have to update theTodoController route handlers for getting all todos and creating a todo to return TodoAPIModel instead of Todo.

现在,您必须更新TodoController路由处理程序以获取所有待办事项并创建待办事项以返回TodoAPIModel而不是Todo

Update existing routes to use `TodoAPIModel` instead of `Todo` 更新现有路由以使用“ TodoAPIModel”而不是“ Todo”

Re-run the project and reload the Todo-Backend tests. You’ll see that we have more tests passing now.

重新运行该项目并重新加载Todo-Backend测试。 您会看到我们现在有更多测试通过。

A todo has an URL, but calling it does not return the TODO yet 待办事项具有URL,但是调用它不会返回TODO

添加端点以获得单个待办事项 (Add endpoint to get a single todo)

Go to TodoController and add a new route handler getSingle(req:).

转到TodoController并添加一个新的路由处理程序getSingle(req:)

TodoController.swift — get single todo route handler TodoController.swift —获取单个待办事项路由处理程序

Add this route and the named parameter todoID to the end of routes.swift:

添加这条路线,并命名参数todoID在2002年底routes.swift

routes.swift — add route with named parameter for `:todoID` route.swift —为`:todoID`添加带有命名参数的路由

Note: you can learn about routes and named parameters in my article Routing in Vapor 4.

注意: 您可以在我的文章 Vapor 4中的路由中 了解路由和命名参数

Re-run the project and reload the Todo-Backend tests.

重新运行该项目并重新加载 Todo-Backend测试。

Todo-Backend is able to fetch a single todo now 待办事项后端现在可以提取单个待办事项

更新待办事项 (Updating a Todo)

The next missing piece is a route that allows Todo-Backend to update a todo’s title and change the value of completed. For this, we have to implement a new route PATCH /todos/{todoID} and we introduce a new PatchTodoRequestBody with optional fields.

下一个缺少的部分是一条路线,该路线允许Todo-Backend更新待办事项的title并更改completed的值。 为此,我们必须实现新的路由PATCH /todos/{todoID}并引入带有可选字段的新PatchTodoRequestBody

What are we doing here?

我们在这里做什么?

// 1.) We check if we can find a todo with todoID.

// 1.)我们检查是否可以找到具有todoID的待办事项。

// 2.) Decode the request body into PatchTodoRequestBody.

// 2.)将请求主体解码为PatchTodoRequestBody

// 3.) Find the todo in our database

// 3.)在我们的数据库中找到待办事项

// 4.) Update title if provided

// 4.)更新title如果提供)

// 5.) Update completed if provided

// 5.)更新completed如果提供)

// 6.) Save changes to database

// 6.)将更改保存到数据库

// 7.) Return our TodoAPIModel

// 7.)返回我们的TodoAPIModel

Now, we add the new route to routes.swift:

现在,我们将新路线添加到routes.swift

We re-run the project and reload the Todo-Backend tests:

我们重新运行项目并重新加载 Todo-Backend测试:

Wow! Only 3 failing tests now! 哇! 现在只有3个失败的测试!

允许订购待办事项 (Allow ordering the todos)

Todo-Backend wants to be able to order our todos. We have to perform several steps for this:

Todo-Backend希望能够订购我们的待办事项。 为此,我们必须执行几个步骤:

  • Add a new field order to ourTodo model and CreateTodo migration.

    向我们的Todo模型和CreateTodo迁移添加新的现场order

  • Add the new field order to our TodoAPIModel, CreateTodoRequestBody and PatchTodoRequestBody.

    将新的字段order添加到我们的TodoAPIModelCreateTodoRequestBodyPatchTodoRequestBody

  • Update the PATCH todos/:todoID endpoint to allow updating the order.

    更新PATCH todos/:todoID端点以允许更新订单。

更新模型并迁移 (Updating the model and migration)

Add a new optional order field to Todo.swift and update the initializer:

Todo.swift添加一个新的可选order字段并更新初始化程序:

Todo.swift with `order` field 带有`order`字段的Todo.swift

Update the migration in CreateTodo.swift as well:

同时更新CreateTodo.swift的迁移:

Update TodoAPIModel, CreateTodoRequestBody and PatchTodoRequestBody:

更新TodoAPIModelCreateTodoRequestBodyPatchTodoRequestBody

Add `order` to `TodoAPIModel` and update the convenience initializer 在`TodoAPIModel`中添加`order`并更新便利初始化器 Add `order` to `CreateTodoRequestBody` and `PatchTodoRequestBody` 将`order`添加到`CreateTodoRequestBody`和`PatchTodoRequestBody`中

Update the update todo route handler to allow changing the order of an existing todo:

更新更新待办事项路由处理程序,以允许更改现有待办事项的顺序:

Now delete the database db.sqlite, re-run the project, and reload the Todo-Backend tests.

现在,删除数据库db.sqlite ,重新运行项目,然后重新加载Todo-Backend测试。

All tests passing ✅ 所有测试通过

That’s it — you did it!

就是这样-您做到了!

You can find the complete source code here: https://github.com/cweinberger/todo-backend-vapor4

您可以在这里找到完整的源代码: https : //github.com/cweinberger/todo-backend-vapor4

I hope you enjoyed my tutorial! If you have any questions, feel free to use the comments section.

希望您喜欢我的教程! 如有任何疑问,请随时使用评论部分。

翻译自: https://medium.com/better-programming/vapor-4-todo-backend-5035c9d7e295

vapor 后端开发

你可能感兴趣的:(python,java,vue,web,ViewUI)