@0xc/serverless-dynamodb-local 中文文档教程

发布于 4年前 浏览 28 项目主页 更新于 3年前

builds.sr.ht status许可证:MIT

@0xc/serverless-dynamodb-local

这是 serverless-dynamodb-local 包的一个分支

This Plugin Requires

  • serverless@^1
  • Java Runtime Engine (JRE) version 6.x or newer

Features

  • Install DynamoDB Local
  • Start DynamoDB Local with all the parameters supported (e.g port, inMemory, sharedDb)
  • Table Creation for DynamoDB Local

Install Plugin

npm install --save serverless-dynamodb-local

然后在serverless.yml 将以下条目添加到插件数组:serverless-dynamodb-local

plugins:
  - serverless-dynamodb-local

Using the Plugin

1) 安装 DynamoDB Local sls dynamodb install

2) 将 DynamoDB 资源定义添加到您的无服务器配置中,如下所定义:https://serverless.com/framework/docs/providers/aws/guide/resources/#configuration

3) 开始DynamoDB 本地和迁移(DynamoDB 将处理传入的请求,直到您停止它。要停止 DynamoDB,请在命令提示符窗口中键入 Ctrl+C)。 确保在此之前执行上述命令。 sls dynamodb start --migrate

注意:阅读详细部分以获取有关高级选项和配置的更多信息。 打开浏览器并转到 url http://localhost:8000/shell 以访问 dynamodb local 的 web shell。

Install: sls dynamodb install

要删除已安装的本地 dynamodb,请运行: sls dynamodb 删除 注意:如果 sls dynamodb 安装在完全删除和安装本地 DynamoDB 的新副本之间失败,这将很有用。

Start: sls dynamodb start

所有 CLI 选项都是可选

--port            -p  Port to listen on. Default: 8000
--cors                    -c  Enable CORS support (cross-origin resource sharing) for JavaScript. You must provide a comma-separated "allow" list of specific domains. The default setting for -cors is an asterisk (*), which allows public access.
--inMemory                -i  DynamoDB; will run in memory, instead of using a database file. When you stop DynamoDB;, none of the data will be saved. Note that you cannot specify both -dbPath and -inMemory at once.
--dbPath                  -d  The directory where DynamoDB will write its database file. If you do not specify this option, the file will be written to the current directory. Note that you cannot specify both -dbPath and -inMemory at once. For the path, current working directory is <projectroot>/node_modules/serverless-dynamodb-local/dynamob. For example to create <projectroot>/node_modules/serverless-dynamodb-local/dynamob/<mypath> you should specify -d <mypath>/ or --dbPath <mypath>/ with a forwardslash at the end.
--sharedDb                -h  DynamoDB will use a single database file, instead of using separate files for each credential and region. If you specify -sharedDb, all DynamoDB clients will interact with the same set of tables regardless of their region and credential configuration.
--delayTransientStatuses  -t  Causes DynamoDB to introduce delays for certain operations. DynamoDB can perform some tasks almost instantaneously, such as create/update/delete operations on tables and indexes; however, the actual DynamoDB service requires more time for these tasks. Setting this parameter helps DynamoDB simulate the behavior of the Amazon DynamoDB web service more closely. (Currently, this parameter introduces delays only for global secondary indexes that are in either CREATING or DELETING status.)
--optimizeDbBeforeStartup -o  Optimizes the underlying database tables before starting up DynamoDB on your computer. You must also specify -dbPath when you use this parameter.
--migration               -m  After starting dynamodb local, run dynamodb migrations.
--heapInitial                 The initial heap size
--heapMax                     The maximum heap size
--migrate                 -m  After starting DynamoDB local, create DynamoDB tables from the Serverless configuration.
--seed                    -s  After starting and migrating dynamodb local, injects seed data into your tables. The --seed option determines which data categories to onload.
--convertEmptyValues      -e  Set to true if you would like the document client to convert empty values (0-length strings, binary buffers, and sets) to be converted to NULL types when persisting to DynamoDB.

的:以上所有选项都可以添加到 serverless.yml 以设置默认配置:例如

custom:
  dynamodb:
  # If you only want to use DynamoDB Local in some stages, declare them here
    stages:
      - dev
    start:
      port: 8000
      inMemory: true
      heapInitial: 200m
      heapMax: 1g
      migrate: true
      seed: true
      convertEmptyValues: true
    # Uncomment only if you already have a DynamoDB running locally
    # noStart: true

Migrations: sls dynamodb migrate

Configuration

,在 serverless.yml 中添加以下内容以在 DynamoDB Local Start 上执行所有迁移

custom:
  dynamodb:
    start:
      migrate: true

AWS::DynamoDB::Table Resource Template for serverless.yml

resources:
  Resources:
    usersTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: usersTable
        AttributeDefinitions:
          - AttributeName: email
            AttributeType: S
        KeySchema:
          - AttributeName: email
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1

注意: DynamoDB 本地不支持 TTL 规范,因此插件将简单地忽略来自 Cloudformation 模板的 ttl 配置。

Seeding: sls dynamodb seed

Configuration

serverless.yml 中,播种类别在 dynamodb.seed 下定义。

如果 dynamodb.start.seed 为真,则在表迁移后执行种子设定。

如果您希望使用原始 AWS AttributeValues 来指定种子数据而不是 Javascript 类型,则只需将任何此类 json 文件的变量从 sources: 更改为 rawsources:

custom:
  dynamodb:
    start:
      seed: true

    seed:
      domain:
        sources:
          - table: domain-widgets
            sources: [./domainWidgets.json]
          - table: domain-fidgets
            sources: [./domainFidgets.json]
      test:
        sources:
          - table: users
            rawsources: [./fake-test-users.json]
          - table: subscriptions
            sources: [./fake-test-subscriptions.json]
> sls dynamodb seed --seed=domain,test
> sls dynamodb start --seed=domain,test

如果种子配置设置为 true,您的配置将在启动时自动播种。 您还可以将种子设置为 false 以防止初始播种以通过 cli 使用手动播种。

```fake-test-users.json 示例 [ { “id”:“约翰”, "name": "母鹿", }, ]

## Using DynamoDB Local in your code
You need to add the following parameters to the AWS NODE SDK dynamodb constructor

e.g. for dynamodb document client sdk

var AWS = require('aws-sdk');

```
new AWS.DynamoDB.DocumentClient({
    region: 'localhost',
    endpoint: 'http://localhost:8000',
    accessKeyId: 'DEFAULT_ACCESS_KEY',  // needed if you don't have aws credentials at all in env
    secretAccessKey: 'DEFAULT_SECRET' // needed if you don't have aws credentials at all in env
})

eg for dynamodb document client sdk

new AWS.DynamoDB({
    region: 'localhost',
    endpoint: 'http://localhost:8000',
    accessKeyId: 'DEFAULT_ACCESS_KEY',  // needed if you don't have aws credentials at all in env
    secretAccessKey: 'DEFAULT_SECRET' // needed if you don't have aws credentials at all in env

})

Using with serverless-offline plugin

将此插件与serverless-offline一起使用时,很难使用上述语法,因为代码应使用DynamoDB Local进行开发,并在AWS中配置后使用DynamoDB Online。 因此我们建议您在代码中使用 serverless-dynamodb-client 插件。

serverless dynamodb start 命令可以在使用 serverless-offline 插件时自动触发。 请注意,您仍然需要先安装 DynamoDB Local。

将这两个插件添加到您的 serverless.yml 文件中:

plugins:
  - serverless-dynamodb-local
  - serverless-offline

确保 serverless-dynamodb-local 位于 serverless-offline 之上,以便更早加载.

现在,您的本地 DynamoDB 数据库将在运行 serverless offline 之前自动启动。

Using with serverless-offline and serverless-webpack plugin

运行 serverless offline start。 与 serverless offline 相比,start 命令将触发一个 init 和一个 end 生命周期钩子,这是需要的serverless-offline 和 serverless-dynamodb-local 关闭这两个资源。

将插件添加到您的 serverless.yml 文件:

plugins:
  - serverless-webpack
  - serverless-dynamodb-local
  - serverless-offline #serverless-offline needs to be last in the list

Reference Project

License

MIT

builds.sr.ht statusLicense: MIT

@0xc/serverless-dynamodb-local

This is a fork of the serverless-dynamodb-local package

This Plugin Requires

  • serverless@^1
  • Java Runtime Engine (JRE) version 6.x or newer

Features

  • Install DynamoDB Local
  • Start DynamoDB Local with all the parameters supported (e.g port, inMemory, sharedDb)
  • Table Creation for DynamoDB Local

Install Plugin

npm install --save serverless-dynamodb-local

Then in serverless.yml add following entry to the plugins array: serverless-dynamodb-local

plugins:
  - serverless-dynamodb-local

Using the Plugin

1) Install DynamoDB Local sls dynamodb install

2) Add DynamoDB Resource definitions to your Serverless configuration, as defined here: https://serverless.com/framework/docs/providers/aws/guide/resources/#configuration

3) Start DynamoDB Local and migrate (DynamoDB will process incoming requests until you stop it. To stop DynamoDB, type Ctrl+C in the command prompt window). Make sure above command is executed before this. sls dynamodb start --migrate

Note: Read the detailed section for more information on advanced options and configurations. Open a browser and go to the url http://localhost:8000/shell to access the web shell for dynamodb local.

Install: sls dynamodb install

To remove the installed dynamodb local, run: sls dynamodb remove Note: This is useful if the sls dynamodb install failed in between to completely remove and install a new copy of DynamoDB local.

Start: sls dynamodb start

All CLI options are optional:

--port            -p  Port to listen on. Default: 8000
--cors                    -c  Enable CORS support (cross-origin resource sharing) for JavaScript. You must provide a comma-separated "allow" list of specific domains. The default setting for -cors is an asterisk (*), which allows public access.
--inMemory                -i  DynamoDB; will run in memory, instead of using a database file. When you stop DynamoDB;, none of the data will be saved. Note that you cannot specify both -dbPath and -inMemory at once.
--dbPath                  -d  The directory where DynamoDB will write its database file. If you do not specify this option, the file will be written to the current directory. Note that you cannot specify both -dbPath and -inMemory at once. For the path, current working directory is <projectroot>/node_modules/serverless-dynamodb-local/dynamob. For example to create <projectroot>/node_modules/serverless-dynamodb-local/dynamob/<mypath> you should specify -d <mypath>/ or --dbPath <mypath>/ with a forwardslash at the end.
--sharedDb                -h  DynamoDB will use a single database file, instead of using separate files for each credential and region. If you specify -sharedDb, all DynamoDB clients will interact with the same set of tables regardless of their region and credential configuration.
--delayTransientStatuses  -t  Causes DynamoDB to introduce delays for certain operations. DynamoDB can perform some tasks almost instantaneously, such as create/update/delete operations on tables and indexes; however, the actual DynamoDB service requires more time for these tasks. Setting this parameter helps DynamoDB simulate the behavior of the Amazon DynamoDB web service more closely. (Currently, this parameter introduces delays only for global secondary indexes that are in either CREATING or DELETING status.)
--optimizeDbBeforeStartup -o  Optimizes the underlying database tables before starting up DynamoDB on your computer. You must also specify -dbPath when you use this parameter.
--migration               -m  After starting dynamodb local, run dynamodb migrations.
--heapInitial                 The initial heap size
--heapMax                     The maximum heap size
--migrate                 -m  After starting DynamoDB local, create DynamoDB tables from the Serverless configuration.
--seed                    -s  After starting and migrating dynamodb local, injects seed data into your tables. The --seed option determines which data categories to onload.
--convertEmptyValues      -e  Set to true if you would like the document client to convert empty values (0-length strings, binary buffers, and sets) to be converted to NULL types when persisting to DynamoDB.

All the above options can be added to serverless.yml to set default configuration: e.g.

custom:
  dynamodb:
  # If you only want to use DynamoDB Local in some stages, declare them here
    stages:
      - dev
    start:
      port: 8000
      inMemory: true
      heapInitial: 200m
      heapMax: 1g
      migrate: true
      seed: true
      convertEmptyValues: true
    # Uncomment only if you already have a DynamoDB running locally
    # noStart: true

Migrations: sls dynamodb migrate

Configuration

In serverless.yml add following to execute all the migration upon DynamoDB Local Start

custom:
  dynamodb:
    start:
      migrate: true

AWS::DynamoDB::Table Resource Template for serverless.yml

resources:
  Resources:
    usersTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: usersTable
        AttributeDefinitions:
          - AttributeName: email
            AttributeType: S
        KeySchema:
          - AttributeName: email
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1

Note: DynamoDB local doesn't support TTL specification, therefore plugin will simply ignore ttl configuration from Cloudformation template.

Seeding: sls dynamodb seed

Configuration

In serverless.yml seeding categories are defined under dynamodb.seed.

If dynamodb.start.seed is true, then seeding is performed after table migrations.

If you wish to use raw AWS AttributeValues to specify your seed data instead of Javascript types then simply change the variable of any such json files from sources: to rawsources:.

custom:
  dynamodb:
    start:
      seed: true

    seed:
      domain:
        sources:
          - table: domain-widgets
            sources: [./domainWidgets.json]
          - table: domain-fidgets
            sources: [./domainFidgets.json]
      test:
        sources:
          - table: users
            rawsources: [./fake-test-users.json]
          - table: subscriptions
            sources: [./fake-test-subscriptions.json]
> sls dynamodb seed --seed=domain,test
> sls dynamodb start --seed=domain,test

If seed config is set to true, your configuration will be seeded automatically on startup. You can also put the seed to false to prevent initial seeding to use manual seeding via cli.

```fake-test-users.json example [ { "id": "John", "name": "Doe", }, ]

## Using DynamoDB Local in your code
You need to add the following parameters to the AWS NODE SDK dynamodb constructor

e.g. for dynamodb document client sdk

var AWS = require('aws-sdk');

```
new AWS.DynamoDB.DocumentClient({
    region: 'localhost',
    endpoint: 'http://localhost:8000',
    accessKeyId: 'DEFAULT_ACCESS_KEY',  // needed if you don't have aws credentials at all in env
    secretAccessKey: 'DEFAULT_SECRET' // needed if you don't have aws credentials at all in env
})

e.g. for dynamodb document client sdk

new AWS.DynamoDB({
    region: 'localhost',
    endpoint: 'http://localhost:8000',
    accessKeyId: 'DEFAULT_ACCESS_KEY',  // needed if you don't have aws credentials at all in env
    secretAccessKey: 'DEFAULT_SECRET' // needed if you don't have aws credentials at all in env

})

Using with serverless-offline plugin

When using this plugin with serverless-offline, it is difficult to use above syntax since the code should use DynamoDB Local for development, and use DynamoDB Online after provisioning in AWS. Therefore we suggest you to use serverless-dynamodb-client plugin in your code.

The serverless dynamodb start command can be triggered automatically when using serverless-offline plugin. Please note that you still need to install DynamoDB Local first.

Add both plugins to your serverless.yml file:

plugins:
  - serverless-dynamodb-local
  - serverless-offline

Make sure that serverless-dynamodb-local is above serverless-offline so it will be loaded earlier.

Now your local DynamoDB database will be automatically started before running serverless offline.

Using with serverless-offline and serverless-webpack plugin

Run serverless offline start. In comparison with serverless offline, the start command will fire an init and a end lifecycle hook which is needed for serverless-offline and serverless-dynamodb-local to switch off both ressources.

Add plugins to your serverless.yml file:

plugins:
  - serverless-webpack
  - serverless-dynamodb-local
  - serverless-offline #serverless-offline needs to be last in the list

Reference Project

License

MIT

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文