Serverless 入门(四)- 如何调试

上两篇文章,我们讲了如何在 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: get
plugins:
  - serverless-offline

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

service: hello-world
provider:
  name: aws
  runtime: nodejs8.10
functions:
  hello:
    handler: index.greeting
    events:
      - http:
          path: hello/{name}
          method: get
plugins:
  - 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 也有。

serverless offline --useSeparateProcesses

相关文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。