本地测试 serverless-offline 与 DynamoDB

该内容并非本站原创,只因原内容字体太小、排版较乱,学习不便,故重新整理发布,如有侵权请联系删除[yestool666#gmial.com] 同时可点击底部github移步出处

接着,让我们用下面的命令,来运行起本地的环境:

$ serverless offline start

Dynamodb Local Started, Visit: http://localhost:8000/shell
Serverless: DynamoDB - created table serverless-rest-api-with-dynamodb-dev
Serverless: Starting Offline: dev/us-east-1.

Serverless: Routes for create:
Serverless: POST /todos

Serverless: Routes for list:
Serverless: GET /todos

Serverless: Routes for get:
Serverless: GET /todos/{id}

Serverless: Routes for update:
Serverless: PUT /todos/{id}

Serverless: Routes for delete:
Serverless: DELETE /todos/{id}

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

启动的时候,发现直接报错了:

  message: 'Missing region in config',
  code: 'ConfigError',
  time: 2017-11-07T01:18:45.365Z }

对比了官方的示例代码后,发现没有对本地调用的 DynamoDB 进行处理:

让我们,新增一个 todos/dynamodb.js 文件:

'use strict';

const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies

let options = {};

// connect to local DB if running offline
if (process.env.IS_OFFLINE) {
  options = {
    region: 'localhost',
    endpoint: 'http://localhost:8000',
  };
}

const client = new AWS.DynamoDB.DocumentClient(options);

module.exports = client;

当我们在本地运行的时候,将使用本地的 DynamoDB,当在服务端运行的时候,则会调用真正的 DynamoDB。

再去修改 create.jsdelete.jsget.jslist.jsupdate.js 中的:

const dynamoDb = new AWS.DynamoDB.DocumentClient();

改为

const dynamoDb = require('./dynamodb');

确认一切无误后,我们就可以使用 postman 测试:

PostMan 测试 Serverless Offline

或者 curl:

curl -X POST -H "Content-Type:application/json" http://localhost:3000/todos --data '{ "text": "Learn Serverless" }'

接着打开本地的 todos 地址:

http://localhost:3000/todos

就会返回类似于在线上生成的数据结果。

[{"checked":false,"createdAt":1510018445663,"id":"be15f600-c35b-11e7-8089-a5ea63a20ab5","text":"Learn Serverless","updatedAt":1510018445663}]

Awesome!

既然,已经有了可以在本地运行 DynamoDB,那么我们是不是可以写上几个测试呢?