aws dynamodb
If we talk about Databases with NestJS you probably already made some connection with MongoDB and mongoose or MySQL and typeorm.
如果我们用NestJS谈论数据库,您可能已经与MongoDB和mongoose或MySQL和typeorm建立了联系。
But if we talk about Serverless with AWS I highly recommend to test DynamoDB.
但是,如果我们谈论使用AWS的无服务器,我强烈建议您测试DynamoDB。
为什么选择DynamoDB? (Why DynamoDB?)
First because is Serverless too! Then there is a lot more information about it here:
首先,因为也是无服务器! 然后,这里有更多关于它的信息:
“Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It’s a fully managed, multiregion, multimaster, durable database with built-in security, backup and restore, and in-memory caching for internet-scale applications. DynamoDB can handle more than 10 trillion requests per day and can support peaks of more than 20 million requests per second.”
“ Amazon DynamoDB是一个键值和文档数据库,可在任何规模上提供单位毫秒的性能。 它是一个完全托管的,多区域,多主机,持久的数据库,具有内置的安全性,备份和还原功能以及用于Internet规模应用程序的内存缓存。 DynamoDB每天可以处理超过10万亿个请求,并且可以支持每秒超过2000万个请求的高峰。”
So it’s fast! Really fast, you can find more information on the page that I posted here.
太快了! 真的很快,您可以在我在此处发布的页面上找到更多信息。
We are going to connect our Serverless NestJS App with our Dynamo DB.
我们将把无服务器NestJS应用程序与Dynamo数据库连接起来。
The objective of this article is that you can connect your NestJS Serverless application with DynamoDB, I will leave you the link to the repository where you can see all the code so that you can download and use it, remember that you must configure an AWS account using the command:
本文的目的是您可以将NestJS Serverless应用程序与DynamoDB连接,我将留下指向存储库的链接,您可以在其中查看所有代码,以便可以下载和使用它,请记住,您必须配置一个AWS账户使用命令:
aws configure
We are going to create a simple application with 2 endpoints, the first one to create an order with a title and a category and the second one to get a created order by id.
我们将创建一个具有2个端点的简单应用程序,第一个端点创建带有标题和类别的订单,第二个端点通过id获取创建的订单。
第一步:NestJS (First Steps: NestJS)
We need to create the stack with our lovely command and our serverless.yml file.
我们需要使用可爱的命令和serverless.yml文件创建堆栈。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/9155bef6944f5bbaefb061ee009d575e.png)
So first let’s talk a little about how I organize a NestJS application:
因此,首先让我们谈谈如何组织NestJS应用程序:
A NestJS application basically works with a module, service and controller logic.
NestJS应用程序基本上可以与模块,服务和控制器逻辑一起使用。
I also use a repository file, the repository files are used with typeorm and entities for MySQL, I also use this with MongoDB and all my projects, It seems to me that it is much more orderly.
我还使用了一个存储库文件,该存储库文件与MySQL的typeorm和实体一起使用,也与MongoDB和我的所有项目一起使用,在我看来,它更有序。
I use the .service.ts for the business logic and the repository for every type of connection to a Database or external API, that way is decoupled and I don’t have to change a lot of logic if I change the DB for example.
我将.service.ts用于业务逻辑,并将存储库用于与数据库或外部API的每种类型的连接,这种方式是分离的,例如,如果我更改数据库,则不必更改很多逻辑。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/3420839b82443989e8efb5c6d0427eb0.png)
So, now that we already have our base files and NestJS application ok, we need to use serverless to deploy our stack.
因此,现在我们已经有了基本文件和NestJS应用程序,我们需要使用无服务器部署堆栈。
去无服务器! (Go Serverless!)
To deploy our stack we are going to use serverless!
要部署我们的堆栈,我们将使用无服务器!
First we need to create our serverless.yml file and configure it to deploy our application:
首先,我们需要创建serverless.yml文件并将其配置为部署我们的应用程序:
So we need to give a name to our application and most important we need to create our DynamoDB Table.
因此,我们需要给应用程序起一个名字,最重要的是,我们需要创建DynamoDB表。
As you already see on the NestJS Files image, we need to create two folders, one folder for the AWS IAM Roles and the other for the AWS Resources.
如您在NestJS文件图像上所看到的,我们需要创建两个文件夹,一个文件夹用于AWS IAM角色,另一个文件夹用于AWS资源。
Let’s look at the provider section of the yml, we have our environment variables where is our ORDERS_TABLE_NAME and our iamRoleStatements pointing to the file with the IAMRole for the OrdersTable.
让我们看一下yml的provider部分,我们有我们的环境变量,我们的ORDERS_TABLE_NAME和iamRoleStatements指向带有IAMRole的OrdersTable文件。
Also we have a custom section, on this custom section you can add everything you need, for example the OrdersTable name and arn that we are going to take once we deploy our application.
我们还有一个自定义部分,在该自定义部分上,您可以添加所需的所有内容,例如在部署应用程序后将要使用的OrdersTable名称和arn。
You can see the CloudFormation documentation here:
您可以在此处查看CloudFormation文档:
With CloudFormation you can retrieve the name and the arn of your DynamoDB table. So you will have a serverless.yml like this:
使用CloudFormation,您可以检索DynamoDB表的名称和arn。 因此,您将拥有一个serverless.yml,如下所示:
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/b42f9e38ad88542205a34e2b730fa666.png)
We need to create our OrdersTable.yml file too, here we reference our DynamoDB Table and define the AttributeDefinitions, in this case I’m using as Attribute name the “id” of type “S” that means “string” and also I’m defining this id in the KeySchema as HASH that is like a Primary Key. I highly recommend to read DynamoDB Documentation too.
我们也需要创建OrdersTable.yml文件,这里我们引用DynamoDB表并定义AttributeDefinitions,在这种情况下,我将类型“ S”的“ id”用作属性名称,即“ string”,并且m在KeySchema中将此ID定义为类似于主键的HASH。 我强烈建议您也阅读DynamoDB文档。
So you will have a file like this:
因此,您将得到一个像这样的文件:
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/03a9c3dc2fae188d6b3bd2191e8f13f2.png)
Finally we need to create our OrdersTableIAM.yml, this file will allow us to PutItems, Scan, GetItem, UpdateItems and Query them from the DynamoDB table that is defined on Resource pointing to the custom section of the serverless.yml.
最后,我们需要创建OrdersTableIAM.yml,此文件将使我们能够从Resource上定义的DynamoDB表中指向Puttings,Scan,GetItem,UpdateItems并查询它们,该表指向serverless.yml的自定义部分。
In this case we are going tou use PutItem and GetItem only. The file should look like this:
在这种情况下,我们将仅使用PutItem和GetItem。 该文件应如下所示:
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/f10b6cbbcc57fb9e6f4182ac6e46d99f.png)
编码时间 (Time to Code)
So we are finally done with the configurations. Now we need to code our Repository and our Service to use the Controller and expose the endpoints to create an Order and also to Get an Order by Id.
因此,我们终于完成了配置。 现在,我们需要对存储库和服务进行编码,以使用Controller并公开端点以创建订单,以及通过ID获取订单。
I will share with you my Github repository with the example code, so I’m not going to write about all the details of the code, only about the Controller and the Repository, remember the logic of our application described on the NestJS section of the article.
我将与示例代码一起分享我的Github存储库,因此,我将不写代码的所有详细信息,而仅写关于Controller和Repository的信息,请记住我们的应用程序的逻辑(在NestJS部分中进行了介绍)文章。
Order.Module.ts (Order.Module.ts)
Here is the order.module.ts, we are basically providing the order.repository.ts and the order.service.ts.
这是order.module.ts,我们基本上提供了order.repository.ts和order.service.ts。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/a341e9404ea8b5060e4fe163a67a0e3b.png)
Order.Controller.ts (Order.Controller.ts)
Here is the order controller, it is exposed with the order.module.ts that is imported by the app.module.ts.
这是订单控制器,它由app.module.ts导入的order.module.ts公开。
So here we have 2 endpoints:
因此,这里有2个端点:
/createOrder: this a POST method that basically creates the Order and response a true or false depending on the result.
/ createOrder:这是一个POST方法,该方法基本上创建Order并根据结果响应true或false。
/getOrderById/:id: this is a GET method that retrieves an order created by it’s Id.
/ getOrderById /:id:这是一个GET方法,用于检索由其ID创建的订单。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/89cf5bfb04c284dfffc0199a61319045.png)
Order.Repository.ts (Order.Repository.ts)
Finally we have the order.repository.ts, here we import the aws-sdk to use the DynamoDB Client, we also import the uuid to create our unique ids on the DynamoDB, I also use nestjs/common for error handling.
最后,我们有了order.repository.ts,在这里我们导入aws-sdk以使用DynamoDB客户端,我们还导入uuid以在DynamoDB上创建我们唯一的ID,我还使用nestjs / common进行错误处理。
Let’s star for the createOrder method, this receives a createOrderDto that is composed by a title and a category, you can call them directly or use the object destructuring.
让我们看一下createOrder方法,它会接收一个由标题和类别组成的createOrderDto,您可以直接调用它们或使用对象分解。
We define a const variable called newOrder and then we create a instance of the DynamoDB.DocumentClient(), we use a put calling the TableName from our environment defined in the serverless.yml and the Item that is the newOrder variable that we defined before. This is a promise, if everything goes as expected we will have our new Order created in our DynamoDB table.
我们定义一个名为newOrder的const变量,然后创建一个DynamoDB.DocumentClient()的实例,我们使用一个put命令从serverless.yml中定义的环境中调用TableName,而Item是我们之前定义的newOrder变量。 这是一个承诺,如果一切都按预期进行,我们将在DynamoDB表中创建新订单。
For the second method getOrderById that receives the order id, we define a let order variable and we call the DynamoDB.DocumentClient() with the get method using again the TableName and passing the id as object to the Key param, this will return the order that we assign to our order variable.
对于接收订单ID的第二种方法getOrderById,我们定义一个let订单变量,并使用get方法再次使用TableName并将其作为对象传递给Key参数,并使用get方法调用DynamoDB.DocumentClient(),这将返回订单我们分配给我们的订单变量。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/05cddbdaaaf444345b50282c2423fe7a.png)
We all this done, we are ready to deploy our application with the sls deploy command.
完成所有这些操作之后,我们就可以使用sls deploy命令部署应用程序了。
部署应用 (Deploy the Application)
We are done with all the code and configurations, so now we can deploy our Serverless NestJS Application.
我们已经完成了所有代码和配置,因此现在我们可以部署无服务器NestJS应用程序。
sls deploy
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/147b093c3cae61af6159e07d8beba562.png)
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/101bfc4da907cb1cc62d0b63496eb3df.png)
Remember, this command will create the CloudFormation, the Lambda Function, the API Gateway and the DynamoDB Table in your AWS environment using the user that you defined with the aws configure command. Once the process is done you will receive the API url for test it.
请记住,该命令将使用您使用aws configure命令定义的用户在您的AWS环境中创建CloudFormation,Lambda函数,API网关和DynamoDB表。 该过程完成后,您将收到用于测试的API网址。
测试应用 (Test the Application)
Time to test our application, first we need Postman, here is the link in case you don’t have it yet:
是时候测试我们的应用程序了,首先我们需要Postman,如果您还没有的话,这里是链接:
So in Postman we are going to create a POST method with the url replacing the “{proxy+}” with “order/createOrder”, we pass the title and category to our order and hit the Send button. If everything goes as expected we will see this response:
因此,在Postman中,我们将创建一个POST方法,其URL将“ {proxy +}”替换为“ order / createOrder”,然后将标题和类别传递给我们的订单,然后单击“发送”按钮。 如果一切都按预期进行,我们将看到以下响应:
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/7d700d95dfbee5bfe6e43cc2e5f0d575.png)
Eureka! It works! Let’s check our AWS Console.
尤里卡! 有用! 让我们检查一下我们的AWS控制台。
In the AWS Console, go to services and then to DynamoDB, you will see the Table that we created, if you click on “Elements” you will see the Order that we just created.
在AWS控制台中,依次转到服务和DynamoDB,您将看到我们创建的表,如果您单击“元素”,您将看到我们刚刚创建的订单。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/2eeb96a20338eed38437eae3be249ba8.png)
So with the order we can test our second endpoint, click on the Order id and you will see the object, copy the id and let’s try!
因此,有了订单,我们可以测试第二个端点,单击订单ID,您将看到对象,复制ID,然后尝试!
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/a8d85735e35f6aa034d50582b1151c2c.png)
Back in Postman we create a new GET Request with the same endpoint than before, change the “/order/createOrder” for “order/getOrderById/orderId”, replacing the “orderId” with the id that you copied before. Hit Send and voilà!
回到Postman,我们创建一个新的GET请求,该请求具有与以前相同的终结点,将“ / order / createOrder”更改为“ order / getOrderById / orderId”,并将“ orderId”替换为之前复制的ID。 点击发送并瞧瞧!
We receive the Order that we created before.
我们收到之前创建的订单。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/5e99d59a44ffa3679fc0a44d6ff52319.png)
We have our Serverless NestJS application working with DynamoDB!
我们有与DynamoDB一起使用的无服务器NestJS应用程序!
结论 (Conclusion)
DynamoDB is a really powerfull AWS Tool, is really fast and works great with any type of application, one of the cons is that you have to learn how to use it because is a bit different thant MySQL, Postgres, MongoDB and others. I highly encourage you to give it a try.
DynamoDB是一个功能非常强大的AWS工具,速度非常快,并且可以与任何类型的应用程序一起很好地使用,缺点之一是您必须学习如何使用它,因为它与MySQL,Postgres,MongoDB等不同。 我强烈建议您尝试一下。
If you want more information about Serverless and NestJS, please see my other articles about NestJS and Serverless.
如果您想了解有关Serverless和NestJS的更多信息,请参阅我有关NestJS和Serverless的其他文章。
翻译自: https://medium.com/javascript-in-plain-english/serverless-nestjs-with-aws-dynamodb-e7530ab33c78
aws dynamodb