@aws/dynamodb-data-marshaller

中文文档
0.7.3发布于 2018/08/16Apache-2.0TypeScriptCommonJS近 30 天下载 12.9万

A schema-based data marshaller for Amazon DynamoDB

原始使用文档
文档目录19 节
  1. Getting started
  2. Specifying keys
  3. Supplying defaults
  4. Supported types
  5. Any
  6. Binary
  7. Boolean
  8. Collection
  9. Custom
  10. Date
  11. Document
  12. Hash
  13. List
  14. Map
  15. Null
  16. Number
  17. Set
  18. String
  19. Tuple

Amazon DynamoDB Data Marshaller

Apache 2 License

This library provides an marshallItem and unmarshallItem functions that convert native JavaScript values to DynamoDB AttributeValues and back again, respectively, based on a defined schema. While many JavaScript values map cleanly to DynamoDB data types and vice versa, schemas allow you to losslessly persist any JavaScript type, including dates, class instances, and empty strings.

Getting started

To use the data marshaller, begin by defining a schema that describes the relationship between your application's domain objects and their serialized form in a DynamoDB table:

const schema = {
    foo: {type: 'Binary'},
    bar: {type: 'Boolean'},
    baz: {type: 'String'},
    quux: {
        type: 'Document',
        members: {
            fizz: {type: 'Set', memberType: 'String'},
            buzz: {
                type: 'Tuple',
                members: [
                    {
                        type: 'List',
                        memberType: {type: 'Set', memberType: 'Number'},
                    },
                    {
                        type: 'Map',
                        memberType: {type: 'Date'},
                    }
                ]
            },
        },
    },
};

This schema may be used to marshall JavaScript values to DynamoDB attribute values:

import {marshallItem} from '@aws/dynamodb-data-marshaller';

const marshalled = marshallItem(schema, {
    foo: Uint8Array.from([0xde, 0xad, 0xbe, 0xef]),
    bar: false,
    baz: '',
    quux: {
        fizz: new Set(['a', 'b', 'c']),
        buzz: [
            [
                new Set([1, 2, 3]),
                new Set([2, 3, 4]),
                new Set([3, 4, 5]),
            ],
            new Map([
                ['now', new Date()],
                ['then', new Date(0)],
            ]),
        ]
    }
});

The schema can also be used to unmarshall DynamoDB attribute values back to their original JavaScript representation:

import {unmarshallItem} from '@aws/dynamodb-data-marshaller';

const unmarshalled = unmarshallItem(schema, {
    foo: {B: Uint8Array.from([0xde, 0xad, 0xbe, 0xef])},
    bar: {BOOL: false},
    baz: {NULL: true},
    quux: {
        fizz: {SS: ['a', 'b', 'c']},
        buzz: {
            L: [
                L: [
                    {NS: ['1', '2', '3']},
                    {NS: ['2', '3', '4']},
                    {NS: ['3', '4', '5']},
                ],
                M: {
                    now: {N: '1507189047'},
                    then: {N: '0'}
                },
            ],
        },
    },
});

Specifying keys

DynamoDB tables must define a hash key and may optionally define a range key. In DynamoDB documentation, these keys are sometimes referred to as partition and sort keys, respectively. To declare a property to be a key, add a keyType property to its property schema (example taken from the DynamoDB developer guide):

// Table model taken from http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html
const gameScores = {
    UserId: {
        type: 'String',
        keyType: 'HASH'
    },
    GameTitle: {
        type: 'String',
        keyType: 'RANGE'
    },
    TopScore: {type: 'Number'},
    TopScoreDateTime: {type: 'Date'},
    Wins: {type: 'Number'},
    Losses: {type: 'Number'}
};

The keyType attribute may only be used in types that are serialized as strings, numbers, or binary attributes. In addition to 'String', 'Number', and 'Binary' properties, it may be used on 'Date' and 'Custom' properties.

Index keys are specified using an object mapping index names to the key type as which the value is used in a given index. To continue with the gameScores example given above, you could add the index key declarations described in the DynamoDB Global Secondary Index developer guide as follows:

const gameScores = {
    UserId: {
        type: 'String',
        keyType: 'HASH'
    },
    GameTitle: {
        type: 'String',
        keyType: 'RANGE',
        indexKeyConfigurations: {
            GameTitleIndex: 'HASH'
        }
    },
    TopScore: {
        type: 'Number',
        indexKeyConfigurations: {
            GameTitleIndex: 'RANGE'
        }
    },
    TopScoreDateTime: {type: 'Date'},
    Wins: {type: 'Number'},
    Losses: {type: 'Number'}
};

Supplying defaults

Any property schema may define a defaultProvider function to be called when a field is undefined in the input provided to marshallItem. This function must return a raw JavaScript value and should not return an already-marshalled DynamoDB AttributeValue shape.

const uuidV4 = require('uuid/v4');

const schema = {
    key: {
        type: 'String',
        defaultProvider: uuidV4,
        keyType: 'HASH',
    },
    // ...
};

Supported types

Any

Will be marshalled and unmarshalled using the @aws/dynamodb-auto-marshaller package, which detects the type of a given value at runtime.

Example

const anyProperty = {
    type: 'Any',
    // optionally, you may specify configuration options for the
    // @aws/dynamodb-auto-marshaller package's Marshaller class:
    unwrapNumbers: false,
    onInvalid: 'omit',
    onEmpty: 'nullify',
};

Binary

Used for ArrayBuffer and ArrayBufferView objects, as well as Node.JS buffers.

May be used as a table or index key.

Example

const binaryProperty = {type: 'Binary'};

Boolean

Used for true/false values.

Example

const booleanProperty = {type: 'Boolean'};

Collection

Denotes a list of untyped items. The constituent items will be marshalled and unmarshalled using the @aws/dynamodb-auto-marshaller.

Example

const collectionProperty = {
    type: 'Collection',
    // optionally, you may specify configuration options for the
    // @aws/dynamodb-auto-marshaller package's Marshaller class:
    unwrapNumbers: false,
    onInvalid: 'omit',
    onEmpty: 'nullify',
};

Custom

Allows the use of bespoke marshalling and unmarshalling functions. The type definition for a 'Custom' property must include a marshall function that converts the type's JavaScript representation to a DynamoDB AttributeValue and an unmarshall function that converts the AttributeValue back to a JavaScript value.

May be used as a table or index key.

Example

// This custom property handles strings
const customProperty = {
    type: 'Custom',
    marshall(input) {
        return {S: input};
    },
    unmarshall(persistedValue) {
        return persistedValue.S;
    }
};

Date

Used for time data. Dates will be serialized to DynamoDB as epoch timestamps for easy integration with DynamoDB's time-to-live feature. As a result, timezone information will not be persisted.

May be used as a table or index key.

Example

const dateProperty = {type: 'Date'};

Document

Used for object values that have their own schema and (optionally) constructor.

Example

class MyCustomDocument {
    method() {
        // pass
    }
    
    get computedProperty() {
        // pass
    }
}

class documentSchema = {
    fizz: {type: 'String'},
    buzz: {type: 'Number'},
    pop: {type: 'Date'}
}

const documentProperty = {
    type: 'Document',
    members: documentSchema,
    // optionally, you may specify a constructor to use to create the object
    // that will underlie unmarshalled instances. If not specified,
    // Object.create(null) will be used.
    valueConstructor: MyCustomDocument
};

Hash

Used for objects with string keys and untyped values.

Example

const collectionProperty = {
    type: 'Hash',
    // optionally, you may specify configuration options for the
    // @aws/dynamodb-auto-marshaller package's Marshaller class:
    unwrapNumbers: false,
    onInvalid: 'omit',
    onEmpty: 'nullify',
};

List

Used for arrays or iterable objects whose elements are all of the same type.

Example

const listOfStrings = {
    type: 'List',
    memberType: {type: 'String'}
};

Map

Used for Map objects whose values are all of the same type.

Example

const mapOfStrings = {
    type: 'Map',
    memberType: {type: 'String'}
};

Null

Used to serialize null. Often used as a sigil value.

Example

const nullProperty = {type: 'Null'};

Number

Used to serialize numbers.

May be used as a table or index key.

Example

const numberProperty = {type: 'Number'};

Set

Used to serialize sets whose values are all of the same type. DynamoDB allows sets of numbers, sets of strings, and sets of binary values.

Example

const binarySetProperty = {type: 'Set', memberType: 'Binary'};
const numberSetProperty = {type: 'Set', memberType: 'Number'};
const stringSetProperty = {type: 'Set', memberType: 'String'};

String

Used to serialize strings.

May be used as a table or index key.

Example

const stringProperty = {type: 'String'};

Tuple

Used to store arrays that have a specific length and sequence of elements.

Example

const tupleProperty = {
    type: 'Tuple',
    members: [
        {type: 'Boolean'},
        {type: 'String'}
    ]
};

版本与发布记录

@aws/dynamodb-data-marshaller 共发布 13 个版本,首次发布于 2017/11/21;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.7.3latest2018/08/168 年前
0.7.12018/07/218 年前
0.7.02018/07/118 年前
0.6.12018/06/298 年前
0.6.02018/06/178 年前
0.5.02018/05/178 年前

关于 @aws/dynamodb-data-marshaller 的常见问题

@aws/dynamodb-data-marshaller 是什么?

A schema-based data marshaller for Amazon DynamoDB

如何安装 @aws/dynamodb-data-marshaller?

在项目目录运行 npm install @aws/dynamodb-data-marshaller,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:aws-sdk(^2.7.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws/dynamodb-data-marshaller 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws/dynamodb-data-marshaller 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@aws/dynamodb-data-marshaller 可以商用吗?

@aws/dynamodb-data-marshaller 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws/dynamodb-data-marshaller 的下载量有多少?

根据 npm 官方下载统计,@aws/dynamodb-data-marshaller 在 2026/10/08 – 2026/11/06 这 30 天内被下载 129,347 次,日均约 4,312 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws/dynamodb-data-marshaller 还在维护吗?

最新版本 0.7.3 发布于 2018/08/16(8 年前);至今共发布 13 个版本,其中过去 12 个月发布了 0 个;首次发布于 2017/11/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。