Serverless 入门(四)- 如何调试

作者 : 开心源码 本文共3609个字,预计阅读时间需要10分钟 发布时间: 2022-05-12 共176人阅读

上两篇文章,我们讲了如何在 Terminal 里调用服务,只要要输入:serverless invoke -f hello -l -d Kenny锅

那么问题来了,我们要调试时,总不能每次都要部署到 AWS 服务端吧,这样效率比较低!我们能在本地调试好了,最后部署到 AWS 上吗? 答案是:可以!

1.使用 Terminal 调试

这个比较简单,只要在 invoke 后加上 local 就行,具体写法:serverless invoke local -f hello -l -d Kenny锅

就算是这么调试,如同也不太方便,假如能在 Insomnia、Postman 之类的工具调试就好了,当然没问题。但有会略微麻烦一点点。只需跟我下面的步骤,你 5 分钟就能完成。

2. 使用工具调试

2.1 安装 serverless-offline

在 Terminal 里执行:yarn add serverless-offline -D

2.2 修改 serverless.yml

打开根目录下的 serverless.yml,在 handler: 那行下面增加如下配置:

    events:      - http:          path: hello/{name}          method: getplugins:  - serverless-offline

为了减少大家出错的情况,这里给出一律 serverless.yml 内容:

service: hello-worldprovider:  name: aws  runtime: nodejs8.10functions:  hello:    handler: index.greeting    events:      - http:          path: hello/{name}          method: getplugins:  - serverless-offline
2.3 修改 js 文件

增加取值的代码,见:

  const {pathParameters = {}} = event;  const {name = '无名女尸'} = pathParameters;  const message = `你好,${ name }.`;

index.js 完整代码,见:

const greeting = async (event, context) => {  const {pathParameters = {}} = event;  const {name = '无名女尸'} = pathParameters;  const message = `你好,${ name }.`;  return {    statusCode: 200,    body: JSON.stringify({      message    }),  };};module.exports = { greeting };

为什么能接收 name 呢? 由于我们在 serverless.yml 的 path 里配置这个路由,而后即可以在 js 里取值。 顺便提一下 event 和 context 参数吧:

  • event 对象里有用的值并不多,见:
{ headers:   { Host: 'localhost:3000',     'User-Agent': 'insomnia/6.3.2',     Accept: '*/*' },  multiValueHeaders:   { Host: [ 'localhost:3000' ],     'User-Agent': [ 'insomnia/6.3.2' ],     Accept: [ '*/*' ] },  path: '/hello/Kenny',  pathParameters: { name: 'Kenny' },  requestContext:   { accountId: 'offlineContext_accountId',     resourceId: 'offlineContext_resourceId',     apiId: 'offlineContext_apiId',     stage: 'dev',     requestId: 'offlineContext_requestId_6815488628284807',     identity:      { cognitoIdentityPoolId: 'offlineContext_cognitoIdentityPoolId',        accountId: 'offlineContext_accountId',        cognitoIdentityId: 'offlineContext_cognitoIdentityId',        caller: 'offlineContext_caller',        apiKey: 'offlineContext_apiKey',        sourceIp: '127.0.0.1',        cognitoAuthenticationType: 'offlineContext_cognitoAuthenticationType',        cognitoAuthenticationProvider: 'offlineContext_cognitoAuthenticationProvider',        userArn: 'offlineContext_userArn',        userAgent: 'insomnia/6.3.2',        user: 'offlineContext_user' },     authorizer:      { principalId: 'offlineContext_authorizer_principalId',        claims: undefined },     protocol: 'HTTP/1.1',     resourcePath: '/hello/{name}',     httpMethod: 'GET' },  resource: '/hello/{name}',  httpMethod: 'GET',  queryStringParameters: null,  multiValueQueryStringParameters: null,  stageVariables: null,  body: null,  isOffline: true }
  • context 里有用的东西就更少了,见:
{ done: [Function],  succeed: [Function: succeed],  fail: [Function: fail],  getRemainingTimeInMillis: [Function: getRemainingTimeInMillis],  functionName: 'hello-world-dev-hello',  memoryLimitInMB: undefined,  functionVersion: 'offline_functionVersion_for_hello-world-dev-hello',  invokedFunctionArn: 'offline_invokedFunctionArn_for_hello-world-dev-hello',  awsRequestId: 'offline_awsRequestId_7983077759511026',  logGroupName: 'offline_logGroupName_for_hello-world-dev-hello',  logStreamName: 'offline_logStreamName_for_hello-world-dev-hello',  identity: {},  clientContext: {} }

为了让大家跟我的目录保持一致,下面列出我的项目结构:

├── index.js├── node_modules├── package.json├── serverless.yml└── yarn.lock
2.4 启动服务

现在来试试吧,在 Terminal 里执行:sls offline。假如启动成功,会在3000 端口上启动服务,见:

Serverless: Starting Offline: dev/us-east-1.Serverless: Routes for hello:Serverless: GET /hello/{name}Serverless: Offline listening on http://localhost:3000

这个时候,我们即可以在 Insomnia 里输入:http://localhost:3000/hello/Kenny,见:

由于是 get 请求,所以用浏览器也可以打开。

2.5 自动重载代码

我们总是想尽一切办法提升工作、开发效率,比方 webpack 和 nodemon 有 reload 的功能,当然 serverless-offline 也有。

先卖个关子,假如到 10 个赞,我就放出来这个技巧,能让你提前 30 分钟下班 ^ _ ^

相关文章

  • Serverless 入门(一) – 创立 IAM https://www.songma.com/p/9fb731a799e2
  • Serverless 入门(二) – HelloWord https://www.songma.com/p/ddf2ffda5f63
  • Serverless 入门(三)- 初始项目解读 https://www.songma.com/p/8baba2a8fe9f
  • Serverless 入门(四)- 如何调试 https://www.songma.com/p/58d30915de8a

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Serverless 入门(四)- 如何调试

发表回复