[英]Differences in designing a serverless function vs. regular server
I am wondering what approach in designing serverless functions to take, while taking designing a regular server as a point of reference.我想知道在设计无服务器功能时采用什么方法,同时将设计常规服务器作为参考点。
With a traditional server, one would focus on defining collections and then CRUD operations one can run on each of them (HTTP verbs such as GET or POST).对于传统服务器,人们会专注于定义 collections,然后可以在每个服务器上运行 CRUD 操作(HTTP 动词,例如 GET 或 POST)。 For example, you would have a collection of users
, and you can get all records via app.get('/users', ...)
, get specific one via app.get('/users/{id}', ...)
or create one via app.post('/users', ...)
.例如,您将有一组users
,您可以通过app.get('/users', ...)
获取所有记录,通过app.get('/users/{id}', ...)
或通过app.post('/users', ...)
创建一个。
How differently would you approach designing a serverless function?您设计无服务器 function 的方法有何不同? Specifically:具体来说:
getAllUsers()
when with a regular server you would define collection of users
and then just use GET to specify what you want to do with it.我假设您在使用常规服务器时会使用类似getAllUsers()
的方法来定义users
集合,然后仅使用 GET 来指定您要对其执行的操作。lookupUser()
, endTrialForUser()
(fired if user we got from lookupUser()
has been on trial longer than 7 days) etc. and then run them one after another from the client (deciding if trial should be ended on the client - seems quite unsafe), or would you just create a getUser()
and then handle all the logic there?你会定义一些小函数,比如lookupUser()
, endTrialForUser()
(如果我们从lookupUser()
得到的用户试用时间超过 7 天,就会触发)等等,然后从客户端一个接一个地运行它们(决定是否应该在客户端结束试用 - 似乎很不安全),或者你会创建一个getUser()
然后处理那里的所有逻辑吗?.../users/${id}/accountData
.在无服务器函数中,我们不能真正做任何类似.../users/${id}/accountData
的事情。 How would you go around fetching nested data?您 go 如何获取嵌套数据? Would you just return a complete JSON every time?你会不会每次都返回一个完整的JSON?I have been looking for some comprehensive articles on the matter but no luck.我一直在寻找有关此事的一些综合文章,但没有运气。 Any suggestions?有什么建议么?
This is a very broad question that you've asked.这是您提出的一个非常广泛的问题。 Let me try answering it point by point.让我试着逐点回答。
Firstly, the approach that you're talking about here is the Serverless API
project approach.首先,您在这里谈论的方法是Serverless API
项目方法。 You can clone their sample project to get a better understanding of how you can build REST
apis for performing CRUD
operations.您可以克隆他们的示例项目,以更好地了解如何构建REST
api 来执行CRUD
操作。 Start by installing the SAM cli and then run the following commands.首先安装 SAM cli ,然后运行以下命令。
$ sam init
Which template source would you like to use?
1 - AWS Quick Start Templates
2 - Custom Template Location
Choice: 1
Cloning from https://github.com/aws/aws-sam-cli-app-templates
Choose an AWS Quick Start application template
1 - Hello World Example
2 - Multi-step workflow
3 - Serverless API
4 - Scheduled task
5 - Standalone function
6 - Data processing
7 - Infrastructure event management
8 - Machine Learning
Template: 3
Which runtime would you like to use?
1 - dotnetcore3.1
2 - nodejs14.x
3 - nodejs12.x
4 - python3.9
5 - python3.8
Runtime: 2
Based on your selections, the only Package type available is Zip.
We will proceed to selecting the Package type as Zip.
Based on your selections, the only dependency manager available is npm.
We will proceed copying the template using npm.
Project name [sam-app]: sample-app
-----------------------
Generating application:
-----------------------
Name: sample-app
Runtime: nodejs14.x
Architectures: x86_64
Dependency Manager: npm
Application Template: quick-start-web
Output Directory: .
Next steps can be found in the README file at ./sample-app/README.md
Commands you can use next
=========================
[*] Create pipeline: cd sample-app && sam pipeline init --bootstrap
[*] Test Function in the Cloud: sam sync --stack-name {stack-name} --watch
HTTP
operations with their suitableHTTP verbs
.是的,您应该将您的HTTP
操作与其合适的HTTP verbs
。 This can be configured at the API Gateway and can be checked for in the Lambda code.这可以在 API 网关配置,可以在 Lambda 代码中检查。 Check the source code of handlers & the template.yml
file from the project you've just cloned with SAM
.检查处理程序的源代码和您刚刚使用SAM
克隆的项目中的template.yml
文件。 // src/handlers/get-by-id.js
if (event.httpMethod !== 'GET') {
throw new Error(`getMethod only accepts GET method, you tried: ${event.httpMethod}`);
}
# template.yml
Events:
Api:
Type: Api
Properties:
Path: /{id}
Method: GET
The naming is totally up to the developer.命名完全取决于开发人员。 You can follow the same approach that you're following with your regular server project.您可以采用与常规服务器项目相同的方法。 You can define the handler with name getAllUsers
or users
and then set the path of that resource to GET /users
in the AWS API Gateway
.您可以使用名称getAllUsers
或users
定义处理程序,然后将该资源的路径设置为AWS API Gateway
中的GET /users
。 You can choose theHTTP verbs
of your desire.您可以选择您想要的HTTP verbs
。 Check this tutorial out for better understanding.查看本教程以获得更好的理解。
Again this up to you.这又取决于你。 You can create a single Lambda that handles all that logic or create individual Lambdas that are triggered one after another by the client based on the response from the previous API. I would say, create a single Lambda and just return the cumulative response to reduce the number of requests.您可以创建一个单独的 Lambda 来处理所有这些逻辑,或者创建由客户端根据前一个 API 的响应一个接一个地触发的 Lambda。我会说,创建一个单独的 Lambda 并只返回累积响应以减少请求的数量。 But again, this totally depends on the UI integration.但同样,这完全取决于 UI 集成。 If your screens demand separate API calls, then please, by all means create individual lambdas.如果您的屏幕需要单独的 API 调用,那么请务必创建单独的 lambda。
This is not true.这不是真的。 We can have dynamic routes specified in the API Gateway.我们可以在 API 网关中指定动态路由。 You can easily set wildcards in your routes by using {variableName}
while setting the routes in API Gateway.在 API 网关中设置路由时,您可以使用{variableName}
轻松地在路由中设置通配符。
GET /users/{userId}
The userId
will then be available at your disposal in the lambda function via event.pathParameters
. GET /users/{userId}
然后userId
将通过event.pathParameters
在 lambda function 中供您使用。
GET /users/{userId}?a=x
Similarly, you could even pass query strings and access them via event.queryStringParameters
in code. GET /users/{userId}?a=x
同样,您甚至可以传递查询字符串并通过代码中的event.queryStringParameters
访问它们。 Have a look at working with routes .看看使用路由。
Tutorial: Build a CRUD API with Lambda and DynamoDB 教程:使用 Lambda 和 DynamoDB 构建 CRUD API
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.