Serverless 入門(四)- 如何調(diào)試

上兩篇文章,我們講了如何在 Terminal 里調(diào)用服務(wù),只需要輸入:serverless invoke -f hello -l -d Kenny鍋

那么問題來了,我們要調(diào)試時(shí),總不能每次都要部署到 AWS 服務(wù)端吧,這樣效率比較低!我們能在本地調(diào)試好了,最后部署到 AWS 上嗎? 答案是:可以!

1.使用 Terminal 調(diào)試

這個(gè)比較簡單,只需在 invoke 后加上 local 就行,具體寫法:serverless invoke local -f hello -l -d Kenny鍋

就算是這么調(diào)試,好像也不太方便,如果能在 Insomnia、Postman 之類的工具調(diào)試就好了,當(dāng)然沒問題。但有會(huì)稍微麻煩一點(diǎn)點(diǎn)。只要跟我下面的步驟,你 5 分鐘就能完成。

2. 使用工具調(diào)試

2.1 安裝 serverless-offline

在 Terminal 里執(zhí)行:yarn add serverless-offline -D

2.2 修改 serverless.yml

打開根目錄下的 serverless.yml,在 handler: 那行下面添加如下配置:

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

為了減少大家出錯(cuò)的情況,這里給出全部 serverless.yml 內(nèi)容:

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 呢? 因?yàn)槲覀冊?serverless.yml 的 path 里配置這個(gè)路由,然后就可以在 js 里取值。 順便提一下 event 和 context 參數(shù)吧:

  • 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: {} }

為了讓大家跟我的目錄保持一致,下面列出我的項(xiàng)目結(jié)構(gòu):

├── index.js
├── node_modules
├── package.json
├── serverless.yml
└── yarn.lock

2.4 啟動(dòng)服務(wù)

現(xiàn)在來試試吧,在 Terminal 里執(zhí)行:sls offline。如果啟動(dòng)成功,會(huì)在3000 端口上啟動(dòng)服務(wù),見:

Serverless: Starting Offline: dev/us-east-1.

Serverless: Routes for hello:
Serverless: GET /hello/{name}

Serverless: Offline listening on http://localhost:3000

這個(gè)時(shí)候,我們就可以在 Insomnia 里輸入:http://localhost:3000/hello/Kenny,見:

因?yàn)槭?get 請求,所以用瀏覽器也可以打開。

2.5 自動(dòng)重載代碼

我們總是想盡一切辦法提升工作、開發(fā)效率,比如 webpack 和 nodemon 有 reload 的功能,當(dāng)然 serverless-offline 也有。

serverless offline --useSeparateProcesses

相關(guān)文章

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。