dynamodb-data-types中文文档|dynamodb-data-types js中文教程|解析
动态数据库数据类型
用于帮助表示 DynamoDB 数据类型和记录的 JavaScript 实用程序。
该库的新版本4.0.0 生成 DynamoDB UpdateExpression
。updateExpr()。
介绍
DynamoDB 将 JavaScript 编号表示1
为{N:'1'}
。
此实用程序有助于在此类表示之间进行转换。
JavaScript DynamoDB
------------------------------------------------
-1 {N: '-1'}
'Hello' {S: 'Hello'}
true {BOOL: true}
NULL {NULL: true}
{a:1, b:''} {M: {a: {N: '1'}, b: {S: ''}}}
入门
wrap
,unwrap
转换(编组)JavaScript 数据。
const attr = require('dynamodb-data-types').AttributeValue;
const data = {
id: 10,
food: ['Rice', 33, null],
obj: {a:1, b:true},
};
const wrapped = attr.wrap(data); // wrap (marshall) data to use with DynamoDB
/* Returns:
* {
* id:{N:"10"},
* food:{L:[{S:"Rice"},{N:"33"},{NULL:true}]},
* obj:{M:{a:{N:"1"},b:{BOOL:true}}}
* } */
attr.unwrap(wrapped); // unwrap (unmarshall) data
/* Returns:
* {
* id: 10,
* food: ['Rice', 33, null],
* obj: {a:1, b:true},
* } */
使用wrap1
和unwrap1
用于单个原始值,
attr.wrap1(50); // { N: '50' }
attr.unwrap1({N:'50'}); // 50
updateExpr()
对于 DynamoDB UpdateExpression
使用updateExpr()
产生DynamoDB UpdateExpression
。
const { updateExpr } = require('dynamodb-data-types');
updateExpr() // Call updateExpr()
.set({ a: 'foo' }) // chain multiple clauses
.add({ n: 1 })
.remove('rat', 'bat')
.set({ sky: 'blue'})
.delete({ day: ['Mon'] }) // 'day' is a reserved keyword
.remove('hi')
.expr(); // In the end expr() returns the UpdateExpression
// After .expr(), we cannot chain any more clauses (set,remove,add,delete)
/* Returns:
{
* UpdateExpression: "SET a = :a, sky = :b REMOVE rat, bat, hi ADD n :c DELETE #A :d",
* ExpressionAttributeValues: {":a":{S:"foo"},":b":{S:"blue"},":c":{N:"1"},":d":{SS:["Mon"]}},
* ExpressionAttributeNames:{"#A":"day"}} // Because 'day' is a reserved keyword
* } */
UpdateExpression
子句SET
, REMOVE
, ADD
,DELETE
updateExpr().set()
、remove()
、add()
、delete()
是 DynamoDB 定义的相同子句UpdateExpression
。据说每个子句包含一个或多个action
。有关
更多信息,请参阅AWS 文档。
updateExpr()
处理 DynamoDB 保留关键字。
updateExpr()避免与DynamoDB 保留的关键字发生冲突。为了演示这一点,下面的示例使用了冲突关键字year
。
一个更完整的例子:
const { wrap } = require('dynamodb-data-types').AttributeValue;
const { updateExpr } = require('dynamodb-data-types');
const { DynamoDBClient, UpdateItemCommand, PutItemCommand } = require('@aws-sdk/client-dynamodb');
const TableName = 'FooTable';
const client = new DynamoDBClient({ region: 'us-east-1' });
const updates = updateExpr() // Call updateExpr()
.set({ greet: 'Hello' }) // chain multiple clauses
.remove('foo', 'city')
.add({ age: 1 })
.set({ nick: 'bar' })
.remove('baz')
.delete({ year: [2008] }) // 'year' is a reserved keyword
.add({ amt: 1.5 });
// Use expr() to get the UpdateExpression data structures
const { UpdateExpression, ExpressionAttributeValues, ExpressionAttributeNames } = updates.expr();
// After .expr(), we cannot chain any more clauses (set,remove,add,delete)
/* Generated data structures:
* {
* UpdateExpression:
* 'SET greet = :a, nick = :b REMOVE foo, baz ADD age :c, amt :d DELETE #A :e',
*
* ExpressionAttributeValues: {
* ':a': { S: 'Hello' },
* ':b': { S: 'bar' },
* ':c': { N: '1' },
* ':d': { N: '1.5' },
* ':e': { NS: [Array] }
* },
*
* ExpressionAttributeNames: { '#A': 'year' } // Because year is a reserved keyword
* }
*/
const params = {
TableName,
Key: wrap({ id: 10 }),
UpdateExpression,
ExpressionAttributeValues,
ExpressionAttributeNames,
};
/* TIP: For shorter code, use ...updates.expr()
* const params = {
* TableName,
* Key: wrap({ id: 10 }),
* ...updates.expr()
* };
*/
client.send(new UpdateItemCommand(params));
updateExpr()
避免创建重复值
如下所示,updateExpr()
避免在内部ExpressionAttributeValue
使用创建重复项
===
。
/* Different action values across clauses.
* Hence ExpressionAttributeValues has three items.
*/
const expr0 = updateExpr()
.set({ w: 1 })
.set({ x: 2 })
.add({ y: 3 })
.expr();
// {
// UpdateExpression: 'SET w = :a, x = :b ADD y :c',
// ExpressionAttributeValues: {
// ':a': { N: '1' },
// ':b': { N: '2' },
// ':c': { N: '3' },
// }
// }
/* Identical action values across clauses.
* Hence ExpressionAttributeValues has only one item.
*/
const expr1 = updateExpr()
.set({ w: 1 })
.set({ x: 1 })
.add({ y: 1 })
.expr();
// {
// UpdateExpression: 'SET w = :a, x = :a ADD y :a',
// ExpressionAttributeValues: {
// ':a': { N: '1' }
// }
// }
路线图 TODO
为了避免 ExpressionAttributeValues 中的重复值,除了使用“===”进行严格的相等检查之外,还允许深度相等以避免重复。
下面,所有动作/子句的值都是相同的数组。因此,ExpressionAttributeValues 中应该有 1 个条目。
但是有3个条目。
执行深度相等并确保 ExpressionAttributeValues 中有 1 个条目可能是一个很好的功能。
const expr0 = updateExpr()
.set({ w: [1, 2, 3] })
.set({ x: [1, 2, 3] })
.set({ y: [1, 2, 3] })
.expr();
// {
// UpdateExpression: 'SET w = :a, x = :b, y = :c',
// ExpressionAttributeValues: {
// ':a': { NS: ['1', '2', '3'] },
// ':b': { NS: ['1', '2', '3'] },
// ':c': { NS: ['1', '2', '3'] },
// }
// }
见
实施例/ 01-放和-更新expression.js
用于生成DynamoDB结构的完整的例子UpdateExpression
,
ExpressionAttributeValues
,ExpressionAttributeNames
。
与 Node.js 一起使用
npm install dynamodb-data-types
在 cli 中使用
与 cli 一起使用以获得快速实用程序
npm install -g dynamodb-data-types
dynamo-dt-attr-wrap '{'hello':'world'}'
dynamo-dt-attr-unwrap '{'hello': {'S': 'world'}}'
在浏览器中使用
从dist下载浏览器版本。
浏览器使用注意事项
此库的浏览器版本(使用browserify创建
)尚未经过测试。欢迎为浏览器添加测试的拉取请求(也许使用 phantom.js?)。
浏览器版本从版本2.1.2
开始可用。
浏览器版本的文件大小
该库的浏览器版本是使用Browserify生成的
。
对于3.0.0
此库以后的版本,browserify
将排除
Buffer
相关代码。浏览器端应用程序不太可能使用Buffer
二进制类型。
如果您不需要有关此的详细信息,请跳过下一段。
该库使用节点的Buffer来识别二进制类型。默认情况下,browserify 包含外部Buffer
相关代码,导致浏览器 dist 的文件大小变为 5.4 倍(如果比较min.js
文件则为 6 倍)。从版本3.0.0
开始,browserify 将排除Buffer
相关代码,因为浏览器端代码似乎不太可能检测Buffer
为二进制类型。如果您的浏览器应用程序确实需要,Buffer
您可以尝试使用
dist-with-buffer
例子
- 示例/01-put-and-update-expression.js
- 示例/02-binary-image.js
- 示例/03-explicit-data-type.js
- 示例/04-explicit-preserve-arrays.js
- 示例/浏览器/dynamodb-data-types.html
- 示例/depricated-01-put-update.js
特征
请参阅
docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Types.html
DynamoDb-Data-Types 支持:
- 属性值
- 更新表达式
- 表达式属性值
- 表达式属性名称
- AttributeValueUpdate(已弃用以支持 UpdateExpression)
支持的 AttributeValue 类型
请参阅
docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html
DynamoDb-Data-Types 支持:
- 乙
- 布尔值
- 学士
- 升
- 米
- N
- 国民服役
- 空值
- 秒
- SS
保留数组
(2.1.0 新版本)
考虑以下:
const data = {
alphabets: ['c', 'a', 'b', 'c']
};
wrap(data)
检测alphabets
为SS
. 作为一个集合SS
有两个与数组不同的属性:
- 不保留元素的顺序。
- 不允许重复元素。
从版本2.1.0开始,您可以执行以下操作:
-
wrap(data, {types: {alphabets: 'L'} }
明确告诉 wrap 处理它L
而不是自动检测到的SS
. 同样对于put()
和add()
- 或者,调用
preserveArrays()
将所有数组视为 typeL
。这具有全球影响。
阅读文档和示例了解更多信息。
BOOL
, NULL
, M
,L
支持(2.0.0 版新增)
DynamoDb-Data-Types 2.0.0 版引入了对AttributeValue
类型BOOL
、NULL
、M
、 的支持L
。
M
嵌套数据
使用DynamoDb-Data-Types 用于M
嵌套对象。考虑以下数据:
const data = {
polygon: {
quadrilateral: {
sides: 4
}
}
}
wrap()
将上述数据映射为:
{
'polygon': {
'M': {
'quadrilateral': {
'M': {
'sides': {
'N': '4'
}
}
}
}
}
}
L
for 数组的使用
DynamoDb-Data-Types 用于L
表示混合数组。考虑以下数据:
{
strs: ['abc', 'def'],
nums: [123, 456],
mix: [1, 'abc', true, false, null, [1,2,3]]
}
wrap()
将上述数据映射为:
{
strs: {
SS: ['abc','def']
},
nums: {
NS: ['123','456']
},
mix: {
'L': [
{ N: '1' },
{ S: 'abc' },
{ BOOL: true },
{ BOOL: false },
{ NULL: true },
{ NS: ['1','2','3'] }
]
}
}
检测数据类型
这是简单的检测类型N
,NS
,S
,SS
,NULL
和BOOL
。要检测其他类型 – M
, L
, B
, BS
– 应用简单规则,如下所述。
对于任何给定值val
,wrap()
检测 AWS 数据类型如下:
布尔值、空值、N、S
如何wrap()
检测它们(伪代码):
IF val is typeof boolean
THEN detect as type BOOL
ELSE IF val is null
THEN detect as type NULL
ELSE IF val is typeof number or if val instanceof Number
THEN detect as type N
ELSE IF val is typeof string or if val is instanceof String
THEN detect as type S
乙
如何wrap()
检测类型B
(伪代码):
IF val is instanceof Buffer
THEN detect as type B
可能还有其他类型应该被检测为B
. 如果您有任何建议,请告诉我。
米
如何wrap()
检测类型M
(伪代码):
IF (val is none of: BOOL, NULL, N, S, B)
AND (typeof val === 'object')
THEN detect as type M
ELSE
wrap() ignores val
NS、SS、BS、L
当wrap()
看到一个数组时,这是它的作用(伪代码):
IF val is an Array
IF (every element in Array is type N)
THEN detect as type NS
ELSE IF (every element in Array is type S)
THEN detect as type SS
ELSE IF (every element in Array is type B)
THEN detect as type BS
ELSE
detect as type L
API – 参考文档
全局设置
保留数组()
如果preserveArrays()
被调用,则在被包装的对象中找到的所有数组都被赋予 type L
。换句话说,数组将不再被检测为NS
,
SS
或者BS
指定为L
。
这对于保留重复项和数组中元素的顺序很有用。
const ddt = require('dynamodb-data-types');
ddt.preserveArrays();
此函数旨在调用一次 – 它具有全局效果。
如果这不是需要在全球范围内,可以使用取得类似的效果
options
传递给参数wrap()
,wrap1()
并put()
和add()
。
同样,全球行为preserveArrays()
可以使用重写options
传递给对象 wrap()
,wrap1()
和put()
和add()
。
属性值
Update
DynamoDB 的 updateExpr()
- 更新表达式
- 表达式属性值
- 表达式属性名称
有关详细的使用示例,请参阅上面的updateExpr()。
AttributeValueUpdate(已弃用)
已弃用!请改用updateExpr()。
要使用 AttributeValueUpdate(已弃用),请参阅README-deprecated
属性值
包装(项目[,选项])
将 JavaScript 数据包装(编组)为 DynamoDB 的 AttributeValue 数据类型。
参数
- @param {Object} item 要包装的对象。
- @param {Object} 选项
- @return {Object} DynamoDB 属性值。
选项
-
types
:包含属性名称和该属性的显式类型的对象。当前只有在检测到的类型是数组时才能指定显式类型。可能的值为'NS'
,'SS'
,'BS'
,'L'
选项对象的示例:
// Any property named 'randomList' found in the object (at any depth) is
// specified as 'NS'. This explicit type can be assigned only if `randomList` is
// detected as an array.
// Similarly if 'orderedList' is an array, it gets specified as type 'L'
{
types: {
randomList: 'NS',
orderedList: 'L'
}
}
例子
const attr = require('dynamodb-data-types').AttributeValue;
attr.wrap({name: 'Foo', age: 50});
// {'name':{'S':'Foo'},'age':{'N':'50'}}
attr.wrap({alphabets: ['a', 'b', 'c']});
// {'alphabets':{'SS': ['a','b','c']}}
attr.wrap({alphabets: ['a', 'b', 'c']}, {types: {alphabets:'L'}});
// {'alphabets':{'L': [{'S':'a'},{'S':'b'},{'S': 'c'}]}}
解包(属性值)
将 DynamoDB AttributeValue 解包(解组)到适当的 JavaScript 类型。
参数
- @param {Object} attributeValue 要解包的 DynamoDB AttributeValue。
- @return {Object} 带有属性的解包对象。
例子
const attr = require('dynamodb-data-types').AttributeValue;
attr.unwrap({'name':{'S':'Foo'},'age':{'N':'50'}});
// {name: 'Foo', age: 50}
wrap1(value [, options])
将单个值包装到 DynamoDB 的 AttributeValue 中。
参数
- @param {字符串|数字|数组}
- @param {Object} options 与 wrap() 的选项相同。
- @return {Object} DynamoDB 属性值。
例子
const attr = require('dynamodb-data-types').AttributeValue;
attr.wrap1(50); // {'N':'50'}
attr.wrap1('50'); // {'S':'50'}
unwrap1(属性值)
将单个 DynamoDB 的 AttributeValue 解包为适当的 JavaScript 类型的值。
参数
@param {Object} 属性值 DynamoDB 属性值。@return {String|Number|Array} JavaScript 值。
例子
const attr = require('dynamodb-data-types').AttributeValue;
attr.unwrap1({'N':'50'}); // 50
attr.unwrap1({'S':'50'}); // '50'
DynamoDb-Data-Types 的旧版本
仅当您需要 DynamoDb-Data-Types 1.0.0或更低版本时才阅读此内容。
如果您已经在使用1.0.0或0.2.7版,您可以继续使用。
如果您使用的是 DynamoDb-Data-Types 版本1.0.0或0.2.7,包装/解包B
并且BS
在与AWS SDK 1.xx一起使用时将不起作用,
但应该自动与AWS SDK 2.xx 一起使用,尽管它还没有经过测试。这与 AWS SDK 2.x 版完成的 base64 自动转换有关。请参阅
AWS 升级说明(1.x 到 2.0)。
更改日志
注意:更改日志日期为 yyyy-mm-dd。
版本 4.0.0
- 介绍
updateExpr()
生成UpdateExpression
用于更新项目的DynamoDB 。
版本 3.0.3
- 更新代码示例和文档
在功能上,此版本与之前的 3.0.2 相同
版本 3.0.2
- 更新
lodash
版本(用于测试)。
在功能上,此版本与之前的 3.0.1 相同
版本 3.0.1
- 感谢@bneigher (github.com/bneigher) 作为 CLI 实用程序公开。
在功能上,除了 CLI 实用程序之外,此版本与之前的 3.0.0 相同
版本 3.0.0
- 对于 Node 用户,版本
3.0.0
与2.1.6
- 对于此库的浏览器端版本
- 在版本
3.0.0
以后的Buffer
相关代码已被排除。 min.js
版本的文件大小现在是6.5KB
. 早些时候是40KB
。
- 在版本
版本 2.1.2 – 2.1.6
- 添加/修复测试以提高覆盖率。
- 审阅文档。
2.1.2 至 2.1.6 版本的源代码与 2.1.1 相同。
版本 2.1.2
此版本与 2.1.1 相同,代码没有更改。它只包含浏览器的 JS 构建以及更多测试。
- 使用 browserify 创建一个在浏览器中使用的 dist。
- 更新测试,使用 travis-ci、coverage、istanbul、.jshintrc。
版本 2.1.1
2015-12-18
- 替换 Node 不推荐使用的函数。
版本 2.1.0
2015-08-17
- 调用
preserveArrays()
使用类型L
为数组类型;这保留了数组元素的顺序并允许重复的数组元素,这两者都不能使用集合SS
,NS
或者BS
- 如果在全局范围内不需要(调用preserveArrays),则通过将 opts 传递给
wrap()
、add()
、put()
版本 2.0.1
2015-02-15
- 固定自述文件
- 提交修改后的package.json(才发现没有提交)
版本 2.0.0
2015-02-15
- 实施
M
- 实施的
L
- 添加了放置和获取二进制数据的示例 (examples/02-binary-image.js)
版本 1.0.0
2015-02-11
注意:版本 1.0.0 中没有源代码更改。在功能上,1.0.0 与 0.2.7 相同。
- 从 0.2.7 版升级到 1.0.0 版。
- 更新文档,尤其是关于
B
和BS
数据类型。 - 将开发部门添加到 pacakge.json 而不是 tests/package.json (应该是这样开始的)
版本 0.2.7
2014-01-29
版本 0.2.6
2013-11-15
版本 0.2.5
2013-11-11