Send to zulip

This commit is contained in:
Koper
2023-11-20 21:39:33 +07:00
parent 82f50817f8
commit ba40d28152
3609 changed files with 2311843 additions and 7 deletions

View File

@@ -0,0 +1,27 @@
import DynamoDB = require('../../clients/dynamodb');
export class Converter {
static input(
data: any,
options?: Converter.ConverterOptions
): DynamoDB.AttributeValue;
static marshall(
data: {[key: string]: any},
options?: Converter.ConverterOptions
): DynamoDB.AttributeMap;
static output(
data: DynamoDB.AttributeValue,
options?: Converter.ConverterOptions
): any;
static unmarshall(
data: DynamoDB.AttributeMap,
options?: Converter.ConverterOptions
): {[key: string]: any};
}
export namespace Converter {
export type ConverterOptions = DynamoDB.DocumentClient.ConverterOptions;
}

View File

@@ -0,0 +1,294 @@
var AWS = require('../core');
var util = AWS.util;
var typeOf = require('./types').typeOf;
var DynamoDBSet = require('./set');
var NumberValue = require('./numberValue');
AWS.DynamoDB.Converter = {
/**
* Convert a JavaScript value to its equivalent DynamoDB AttributeValue type
*
* @param data [any] The data to convert to a DynamoDB AttributeValue
* @param options [map]
* @option options convertEmptyValues [Boolean] Whether to automatically
* convert empty strings, blobs,
* and sets to `null`
* @option options wrapNumbers [Boolean] Whether to return numbers as a
* NumberValue object instead of
* converting them to native JavaScript
* numbers. This allows for the safe
* round-trip transport of numbers of
* arbitrary size.
* @return [map] An object in the Amazon DynamoDB AttributeValue format
*
* @see AWS.DynamoDB.Converter.marshall AWS.DynamoDB.Converter.marshall to
* convert entire records (rather than individual attributes)
*/
input: function convertInput(data, options) {
options = options || {};
var type = typeOf(data);
if (type === 'Object') {
return formatMap(data, options);
} else if (type === 'Array') {
return formatList(data, options);
} else if (type === 'Set') {
return formatSet(data, options);
} else if (type === 'String') {
if (data.length === 0 && options.convertEmptyValues) {
return convertInput(null);
}
return { S: data };
} else if (type === 'Number' || type === 'NumberValue') {
return { N: data.toString() };
} else if (type === 'Binary') {
if (data.length === 0 && options.convertEmptyValues) {
return convertInput(null);
}
return { B: data };
} else if (type === 'Boolean') {
return { BOOL: data };
} else if (type === 'null') {
return { NULL: true };
} else if (type !== 'undefined' && type !== 'Function') {
// this value has a custom constructor
return formatMap(data, options);
}
},
/**
* Convert a JavaScript object into a DynamoDB record.
*
* @param data [any] The data to convert to a DynamoDB record
* @param options [map]
* @option options convertEmptyValues [Boolean] Whether to automatically
* convert empty strings, blobs,
* and sets to `null`
* @option options wrapNumbers [Boolean] Whether to return numbers as a
* NumberValue object instead of
* converting them to native JavaScript
* numbers. This allows for the safe
* round-trip transport of numbers of
* arbitrary size.
*
* @return [map] An object in the DynamoDB record format.
*
* @example Convert a JavaScript object into a DynamoDB record
* var marshalled = AWS.DynamoDB.Converter.marshall({
* string: 'foo',
* list: ['fizz', 'buzz', 'pop'],
* map: {
* nestedMap: {
* key: 'value',
* }
* },
* number: 123,
* nullValue: null,
* boolValue: true,
* stringSet: new DynamoDBSet(['foo', 'bar', 'baz'])
* });
*/
marshall: function marshallItem(data, options) {
return AWS.DynamoDB.Converter.input(data, options).M;
},
/**
* Convert a DynamoDB AttributeValue object to its equivalent JavaScript type.
*
* @param data [map] An object in the Amazon DynamoDB AttributeValue format
* @param options [map]
* @option options convertEmptyValues [Boolean] Whether to automatically
* convert empty strings, blobs,
* and sets to `null`
* @option options wrapNumbers [Boolean] Whether to return numbers as a
* NumberValue object instead of
* converting them to native JavaScript
* numbers. This allows for the safe
* round-trip transport of numbers of
* arbitrary size.
*
* @return [Object|Array|String|Number|Boolean|null]
*
* @see AWS.DynamoDB.Converter.unmarshall AWS.DynamoDB.Converter.unmarshall to
* convert entire records (rather than individual attributes)
*/
output: function convertOutput(data, options) {
options = options || {};
var list, map, i;
for (var type in data) {
var values = data[type];
if (type === 'M') {
map = {};
for (var key in values) {
map[key] = convertOutput(values[key], options);
}
return map;
} else if (type === 'L') {
list = [];
for (i = 0; i < values.length; i++) {
list.push(convertOutput(values[i], options));
}
return list;
} else if (type === 'SS') {
list = [];
for (i = 0; i < values.length; i++) {
list.push(values[i] + '');
}
return new DynamoDBSet(list);
} else if (type === 'NS') {
list = [];
for (i = 0; i < values.length; i++) {
list.push(convertNumber(values[i], options.wrapNumbers));
}
return new DynamoDBSet(list);
} else if (type === 'BS') {
list = [];
for (i = 0; i < values.length; i++) {
list.push(AWS.util.buffer.toBuffer(values[i]));
}
return new DynamoDBSet(list);
} else if (type === 'S') {
return values + '';
} else if (type === 'N') {
return convertNumber(values, options.wrapNumbers);
} else if (type === 'B') {
return util.buffer.toBuffer(values);
} else if (type === 'BOOL') {
return (values === 'true' || values === 'TRUE' || values === true);
} else if (type === 'NULL') {
return null;
}
}
},
/**
* Convert a DynamoDB record into a JavaScript object.
*
* @param data [any] The DynamoDB record
* @param options [map]
* @option options convertEmptyValues [Boolean] Whether to automatically
* convert empty strings, blobs,
* and sets to `null`
* @option options wrapNumbers [Boolean] Whether to return numbers as a
* NumberValue object instead of
* converting them to native JavaScript
* numbers. This allows for the safe
* round-trip transport of numbers of
* arbitrary size.
*
* @return [map] An object whose properties have been converted from
* DynamoDB's AttributeValue format into their corresponding native
* JavaScript types.
*
* @example Convert a record received from a DynamoDB stream
* var unmarshalled = AWS.DynamoDB.Converter.unmarshall({
* string: {S: 'foo'},
* list: {L: [{S: 'fizz'}, {S: 'buzz'}, {S: 'pop'}]},
* map: {
* M: {
* nestedMap: {
* M: {
* key: {S: 'value'}
* }
* }
* }
* },
* number: {N: '123'},
* nullValue: {NULL: true},
* boolValue: {BOOL: true}
* });
*/
unmarshall: function unmarshall(data, options) {
return AWS.DynamoDB.Converter.output({M: data}, options);
}
};
/**
* @api private
* @param data [Array]
* @param options [map]
*/
function formatList(data, options) {
var list = {L: []};
for (var i = 0; i < data.length; i++) {
list['L'].push(AWS.DynamoDB.Converter.input(data[i], options));
}
return list;
}
/**
* @api private
* @param value [String]
* @param wrapNumbers [Boolean]
*/
function convertNumber(value, wrapNumbers) {
return wrapNumbers ? new NumberValue(value) : Number(value);
}
/**
* @api private
* @param data [map]
* @param options [map]
*/
function formatMap(data, options) {
var map = {M: {}};
for (var key in data) {
var formatted = AWS.DynamoDB.Converter.input(data[key], options);
if (formatted !== void 0) {
map['M'][key] = formatted;
}
}
return map;
}
/**
* @api private
*/
function formatSet(data, options) {
options = options || {};
var values = data.values;
if (options.convertEmptyValues) {
values = filterEmptySetValues(data);
if (values.length === 0) {
return AWS.DynamoDB.Converter.input(null);
}
}
var map = {};
switch (data.type) {
case 'String': map['SS'] = values; break;
case 'Binary': map['BS'] = values; break;
case 'Number': map['NS'] = values.map(function (value) {
return value.toString();
});
}
return map;
}
/**
* @api private
*/
function filterEmptySetValues(set) {
var nonEmptyValues = [];
var potentiallyEmptyTypes = {
String: true,
Binary: true,
Number: false
};
if (potentiallyEmptyTypes[set.type]) {
for (var i = 0; i < set.values.length; i++) {
if (set.values[i].length === 0) {
continue;
}
nonEmptyValues.push(set.values[i]);
}
return nonEmptyValues;
}
return set.values;
}
/**
* @api private
*/
module.exports = AWS.DynamoDB.Converter;

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,583 @@
var AWS = require('../core');
var Translator = require('./translator');
var DynamoDBSet = require('./set');
/**
* The document client simplifies working with items in Amazon DynamoDB
* by abstracting away the notion of attribute values. This abstraction
* annotates native JavaScript types supplied as input parameters, as well
* as converts annotated response data to native JavaScript types.
*
* ## Marshalling Input and Unmarshalling Response Data
*
* The document client affords developers the use of native JavaScript types
* instead of `AttributeValue`s to simplify the JavaScript development
* experience with Amazon DynamoDB. JavaScript objects passed in as parameters
* are marshalled into `AttributeValue` shapes required by Amazon DynamoDB.
* Responses from DynamoDB are unmarshalled into plain JavaScript objects
* by the `DocumentClient`. The `DocumentClient`, does not accept
* `AttributeValue`s in favor of native JavaScript types.
*
* | JavaScript Type | DynamoDB AttributeValue |
* |:----------------------------------------------------------------------:|-------------------------|
* | String | S |
* | Number | N |
* | Boolean | BOOL |
* | null | NULL |
* | Array | L |
* | Object | M |
* | Buffer, File, Blob, ArrayBuffer, DataView, and JavaScript typed arrays | B |
*
* ## Support for Sets
*
* The `DocumentClient` offers a convenient way to create sets from
* JavaScript Arrays. The type of set is inferred from the first element
* in the array. DynamoDB supports string, number, and binary sets. To
* learn more about supported types see the
* [Amazon DynamoDB Data Model Documentation](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html)
* For more information see {AWS.DynamoDB.DocumentClient.createSet}
*
*/
AWS.DynamoDB.DocumentClient = AWS.util.inherit({
/**
* Creates a DynamoDB document client with a set of configuration options.
*
* @option options params [map] An optional map of parameters to bind to every
* request sent by this service object.
* @option options service [AWS.DynamoDB] An optional pre-configured instance
* of the AWS.DynamoDB service object. This instance's config will be
* copied to a new instance used by this client. You should not need to
* retain a reference to the input object, and may destroy it or allow it
* to be garbage collected.
* @option options convertEmptyValues [Boolean] 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.
* @option options wrapNumbers [Boolean] Set to true to return numbers as a
* NumberValue object instead of converting them to native JavaScript numbers.
* This allows for the safe round-trip transport of numbers of arbitrary size.
* @see AWS.DynamoDB.constructor
*
*/
constructor: function DocumentClient(options) {
var self = this;
self.options = options || {};
self.configure(self.options);
},
/**
* @api private
*/
configure: function configure(options) {
var self = this;
self.service = options.service;
self.bindServiceObject(options);
self.attrValue = options.attrValue =
self.service.api.operations.putItem.input.members.Item.value.shape;
},
/**
* @api private
*/
bindServiceObject: function bindServiceObject(options) {
var self = this;
options = options || {};
if (!self.service) {
self.service = new AWS.DynamoDB(options);
} else {
var config = AWS.util.copy(self.service.config);
self.service = new self.service.constructor.__super__(config);
self.service.config.params =
AWS.util.merge(self.service.config.params || {}, options.params);
}
},
/**
* @api private
*/
makeServiceRequest: function(operation, params, callback) {
var self = this;
var request = self.service[operation](params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* @api private
*/
serviceClientOperationsMap: {
batchGet: 'batchGetItem',
batchWrite: 'batchWriteItem',
delete: 'deleteItem',
get: 'getItem',
put: 'putItem',
query: 'query',
scan: 'scan',
update: 'updateItem',
transactGet: 'transactGetItems',
transactWrite: 'transactWriteItems'
},
/**
* Returns the attributes of one or more items from one or more tables
* by delegating to `AWS.DynamoDB.batchGetItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.batchGetItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.batchGetItem
* @example Get items from multiple tables
* var params = {
* RequestItems: {
* 'Table-1': {
* Keys: [
* {
* HashKey: 'haskey',
* NumberRangeKey: 1
* }
* ]
* },
* 'Table-2': {
* Keys: [
* { foo: 'bar' },
* ]
* }
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.batchGet(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
batchGet: function(params, callback) {
var operation = this.serviceClientOperationsMap['batchGet'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Puts or deletes multiple items in one or more tables by delegating
* to `AWS.DynamoDB.batchWriteItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.batchWriteItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.batchWriteItem
* @example Write to and delete from a table
* var params = {
* RequestItems: {
* 'Table-1': [
* {
* DeleteRequest: {
* Key: { HashKey: 'someKey' }
* }
* },
* {
* PutRequest: {
* Item: {
* HashKey: 'anotherKey',
* NumAttribute: 1,
* BoolAttribute: true,
* ListAttribute: [1, 'two', false],
* MapAttribute: { foo: 'bar' }
* }
* }
* }
* ]
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.batchWrite(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
batchWrite: function(params, callback) {
var operation = this.serviceClientOperationsMap['batchWrite'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Deletes a single item in a table by primary key by delegating to
* `AWS.DynamoDB.deleteItem()`
*
* Supply the same parameters as {AWS.DynamoDB.deleteItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.deleteItem
* @example Delete an item from a table
* var params = {
* TableName : 'Table',
* Key: {
* HashKey: 'hashkey',
* NumberRangeKey: 1
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.delete(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
delete: function(params, callback) {
var operation = this.serviceClientOperationsMap['delete'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Returns a set of attributes for the item with the given primary key
* by delegating to `AWS.DynamoDB.getItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.getItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.getItem
* @example Get an item from a table
* var params = {
* TableName : 'Table',
* Key: {
* HashKey: 'hashkey'
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.get(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
get: function(params, callback) {
var operation = this.serviceClientOperationsMap['get'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Creates a new item, or replaces an old item with a new item by
* delegating to `AWS.DynamoDB.putItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.putItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.putItem
* @example Create a new item in a table
* var params = {
* TableName : 'Table',
* Item: {
* HashKey: 'haskey',
* NumAttribute: 1,
* BoolAttribute: true,
* ListAttribute: [1, 'two', false],
* MapAttribute: { foo: 'bar'},
* NullAttribute: null
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.put(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
put: function(params, callback) {
var operation = this.serviceClientOperationsMap['put'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Edits an existing item's attributes, or adds a new item to the table if
* it does not already exist by delegating to `AWS.DynamoDB.updateItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.updateItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.updateItem
* @example Update an item with expressions
* var params = {
* TableName: 'Table',
* Key: { HashKey : 'hashkey' },
* UpdateExpression: 'set #a = :x + :y',
* ConditionExpression: '#a < :MAX',
* ExpressionAttributeNames: {'#a' : 'Sum'},
* ExpressionAttributeValues: {
* ':x' : 20,
* ':y' : 45,
* ':MAX' : 100,
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.update(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
update: function(params, callback) {
var operation = this.serviceClientOperationsMap['update'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Returns one or more items and item attributes by accessing every item
* in a table or a secondary index.
*
* Supply the same parameters as {AWS.DynamoDB.scan} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.scan
* @example Scan the table with a filter expression
* var params = {
* TableName : 'Table',
* FilterExpression : 'Year = :this_year',
* ExpressionAttributeValues : {':this_year' : 2015}
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.scan(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
scan: function(params, callback) {
var operation = this.serviceClientOperationsMap['scan'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Directly access items from a table by primary key or a secondary index.
*
* Supply the same parameters as {AWS.DynamoDB.query} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.query
* @example Query an index
* var params = {
* TableName: 'Table',
* IndexName: 'Index',
* KeyConditionExpression: 'HashKey = :hkey and RangeKey > :rkey',
* ExpressionAttributeValues: {
* ':hkey': 'key',
* ':rkey': 2015
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.query(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
query: function(params, callback) {
var operation = this.serviceClientOperationsMap['query'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Synchronous write operation that groups up to 100 action requests.
*
* Supply the same parameters as {AWS.DynamoDB.transactWriteItems} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.transactWriteItems
* @example Get items from multiple tables
* var params = {
* TransactItems: [{
* Put: {
* TableName : 'Table0',
* Item: {
* HashKey: 'haskey',
* NumAttribute: 1,
* BoolAttribute: true,
* ListAttribute: [1, 'two', false],
* MapAttribute: { foo: 'bar'},
* NullAttribute: null
* }
* }
* }, {
* Update: {
* TableName: 'Table1',
* Key: { HashKey : 'hashkey' },
* UpdateExpression: 'set #a = :x + :y',
* ConditionExpression: '#a < :MAX',
* ExpressionAttributeNames: {'#a' : 'Sum'},
* ExpressionAttributeValues: {
* ':x' : 20,
* ':y' : 45,
* ':MAX' : 100,
* }
* }
* }]
* };
*
* documentClient.transactWrite(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*/
transactWrite: function(params, callback) {
var operation = this.serviceClientOperationsMap['transactWrite'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Atomically retrieves multiple items from one or more tables (but not from indexes)
* in a single account and region.
*
* Supply the same parameters as {AWS.DynamoDB.transactGetItems} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.transactGetItems
* @example Get items from multiple tables
* var params = {
* TransactItems: [{
* Get: {
* TableName : 'Table0',
* Key: {
* HashKey: 'hashkey0'
* }
* }
* }, {
* Get: {
* TableName : 'Table1',
* Key: {
* HashKey: 'hashkey1'
* }
* }
* }]
* };
*
* documentClient.transactGet(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*/
transactGet: function(params, callback) {
var operation = this.serviceClientOperationsMap['transactGet'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Creates a set of elements inferring the type of set from
* the type of the first element. Amazon DynamoDB currently supports
* the number sets, string sets, and binary sets. For more information
* about DynamoDB data types see the documentation on the
* [Amazon DynamoDB Data Model](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes).
*
* @param list [Array] Collection to represent your DynamoDB Set
* @param options [map]
* * **validate** [Boolean] set to true if you want to validate the type
* of each element in the set. Defaults to `false`.
* @example Creating a number set
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* var params = {
* Item: {
* hashkey: 'hashkey'
* numbers: documentClient.createSet([1, 2, 3]);
* }
* };
*
* documentClient.put(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
createSet: function(list, options) {
options = options || {};
return new DynamoDBSet(list, options);
},
/**
* @api private
*/
getTranslator: function() {
return new Translator(this.options);
},
/**
* @api private
*/
setupRequest: function setupRequest(request) {
var self = this;
var translator = self.getTranslator();
var operation = request.operation;
var inputShape = request.service.api.operations[operation].input;
request._events.validate.unshift(function(req) {
req.rawParams = AWS.util.copy(req.params);
req.params = translator.translateInput(req.rawParams, inputShape);
});
},
/**
* @api private
*/
setupResponse: function setupResponse(request) {
var self = this;
var translator = self.getTranslator();
var outputShape = self.service.api.operations[request.operation].output;
request.on('extractData', function(response) {
response.data = translator.translateOutput(response.data, outputShape);
});
var response = request.response;
response.nextPage = function(cb) {
var resp = this;
var req = resp.request;
var config;
var service = req.service;
var operation = req.operation;
try {
config = service.paginationConfig(operation, true);
} catch (e) { resp.error = e; }
if (!resp.hasNextPage()) {
if (cb) cb(resp.error, null);
else if (resp.error) throw resp.error;
return null;
}
var params = AWS.util.copy(req.rawParams);
if (!resp.nextPageTokens) {
return cb ? cb(null, null) : null;
} else {
var inputTokens = config.inputToken;
if (typeof inputTokens === 'string') inputTokens = [inputTokens];
for (var i = 0; i < inputTokens.length; i++) {
params[inputTokens[i]] = resp.nextPageTokens[i];
}
return self[operation](params, cb);
}
};
}
});
/**
* @api private
*/
module.exports = AWS.DynamoDB.DocumentClient;

View File

@@ -0,0 +1,9 @@
export class NumberValue {
constructor(value: string|number);
toJSON(): number;
toNumber(): number;
toString(): string;
}

View File

@@ -0,0 +1,43 @@
var util = require('../core').util;
/**
* An object recognizable as a numeric value that stores the underlying number
* as a string.
*
* Intended to be a deserialization target for the DynamoDB Document Client when
* the `wrapNumbers` flag is set. This allows for numeric values that lose
* precision when converted to JavaScript's `number` type.
*/
var DynamoDBNumberValue = util.inherit({
constructor: function NumberValue(value) {
this.wrapperName = 'NumberValue';
this.value = value.toString();
},
/**
* Render the underlying value as a number when converting to JSON.
*/
toJSON: function () {
return this.toNumber();
},
/**
* Convert the underlying value to a JavaScript number.
*/
toNumber: function () {
return Number(this.value);
},
/**
* Return a string representing the unaltered value provided to the
* constructor.
*/
toString: function () {
return this.value;
}
});
/**
* @api private
*/
module.exports = DynamoDBNumberValue;

View File

@@ -0,0 +1,71 @@
var util = require('../core').util;
var typeOf = require('./types').typeOf;
/**
* @api private
*/
var memberTypeToSetType = {
'String': 'String',
'Number': 'Number',
'NumberValue': 'Number',
'Binary': 'Binary'
};
/**
* @api private
*/
var DynamoDBSet = util.inherit({
constructor: function Set(list, options) {
options = options || {};
this.wrapperName = 'Set';
this.initialize(list, options.validate);
},
initialize: function(list, validate) {
var self = this;
self.values = [].concat(list);
self.detectType();
if (validate) {
self.validate();
}
},
detectType: function() {
this.type = memberTypeToSetType[typeOf(this.values[0])];
if (!this.type) {
throw util.error(new Error(), {
code: 'InvalidSetType',
message: 'Sets can contain string, number, or binary values'
});
}
},
validate: function() {
var self = this;
var length = self.values.length;
var values = self.values;
for (var i = 0; i < length; i++) {
if (memberTypeToSetType[typeOf(values[i])] !== self.type) {
throw util.error(new Error(), {
code: 'InvalidType',
message: self.type + ' Set contains ' + typeOf(values[i]) + ' value'
});
}
}
},
/**
* Render the underlying values only when converting to JSON.
*/
toJSON: function() {
var self = this;
return self.values;
}
});
/**
* @api private
*/
module.exports = DynamoDBSet;

View File

@@ -0,0 +1,87 @@
var util = require('../core').util;
var convert = require('./converter');
var Translator = function(options) {
options = options || {};
this.attrValue = options.attrValue;
this.convertEmptyValues = Boolean(options.convertEmptyValues);
this.wrapNumbers = Boolean(options.wrapNumbers);
};
Translator.prototype.translateInput = function(value, shape) {
this.mode = 'input';
return this.translate(value, shape);
};
Translator.prototype.translateOutput = function(value, shape) {
this.mode = 'output';
return this.translate(value, shape);
};
Translator.prototype.translate = function(value, shape) {
var self = this;
if (!shape || value === undefined) return undefined;
if (shape.shape === self.attrValue) {
return convert[self.mode](value, {
convertEmptyValues: self.convertEmptyValues,
wrapNumbers: self.wrapNumbers,
});
}
switch (shape.type) {
case 'structure': return self.translateStructure(value, shape);
case 'map': return self.translateMap(value, shape);
case 'list': return self.translateList(value, shape);
default: return self.translateScalar(value, shape);
}
};
Translator.prototype.translateStructure = function(structure, shape) {
var self = this;
if (structure == null) return undefined;
var struct = {};
util.each(structure, function(name, value) {
var memberShape = shape.members[name];
if (memberShape) {
var result = self.translate(value, memberShape);
if (result !== undefined) struct[name] = result;
}
});
return struct;
};
Translator.prototype.translateList = function(list, shape) {
var self = this;
if (list == null) return undefined;
var out = [];
util.arrayEach(list, function(value) {
var result = self.translate(value, shape.member);
if (result === undefined) out.push(null);
else out.push(result);
});
return out;
};
Translator.prototype.translateMap = function(map, shape) {
var self = this;
if (map == null) return undefined;
var out = {};
util.each(map, function(key, value) {
var result = self.translate(value, shape.value);
if (result === undefined) out[key] = null;
else out[key] = result;
});
return out;
};
Translator.prototype.translateScalar = function(value, shape) {
return shape.toType(value);
};
/**
* @api private
*/
module.exports = Translator;

View File

@@ -0,0 +1,49 @@
var util = require('../core').util;
function typeOf(data) {
if (data === null && typeof data === 'object') {
return 'null';
} else if (data !== undefined && isBinary(data)) {
return 'Binary';
} else if (data !== undefined && data.constructor) {
return data.wrapperName || util.typeName(data.constructor);
} else if (data !== undefined && typeof data === 'object') {
// this object is the result of Object.create(null), hence the absence of a
// defined constructor
return 'Object';
} else {
return 'undefined';
}
}
function isBinary(data) {
var types = [
'Buffer', 'File', 'Blob', 'ArrayBuffer', 'DataView',
'Int8Array', 'Uint8Array', 'Uint8ClampedArray',
'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array',
'Float32Array', 'Float64Array'
];
if (util.isNode()) {
var Stream = util.stream.Stream;
if (util.Buffer.isBuffer(data) || data instanceof Stream) {
return true;
}
}
for (var i = 0; i < types.length; i++) {
if (data !== undefined && data.constructor) {
if (util.isType(data, types[i])) return true;
if (util.typeName(data.constructor) === types[i]) return true;
}
}
return false;
}
/**
* @api private
*/
module.exports = {
typeOf: typeOf,
isBinary: isBinary
};