Skip to content

Commit

Permalink
fix(saveunknown): fixing saveunknown toDynamo for maps
Browse files Browse the repository at this point in the history
fix #323
  • Loading branch information
fishcharlie committed Feb 12, 2019
1 parent 59e9422 commit 873a6ed
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 8 deletions.
20 changes: 12 additions & 8 deletions lib/Attribute.js
Expand Up @@ -468,18 +468,22 @@ Attribute.prototype.toDynamo = async function(val, noSet, model, options) {
return v;
}.bind(this));
} else if (type.name === 'map') {

let dynamoMapObj = {};
for(const name in this.attributes) {
const attr = this.attributes[name];
await attr.setDefault(model);
const dynamoAttr = await attr.toDynamo(val[name], undefined, model);
if(dynamoAttr) {
dynamoMapObj[attr.name] = dynamoAttr;
for(const [name, value] of Object.entries(val)) {
let subAttr = this.attributes[name];
// if saveUnknown is activated the input has an unknown attribute, let's create one on the fly.
if (!subAttr && (this.schema.options.saveUnknown || Array.isArray(this.options.saveUnknown) && this.options.saveUnknown.indexOf(name) >= 0)) {
subAttr = module.exports.create(this.schema, name, value);
this.attributes[name] = subAttr;
}
if (subAttr) {
const attrVal = await subAttr.toDynamo(value);
if (attrVal !== undefined && attrVal !== null) {
dynamoMapObj[name] = attrVal;
}
}
}
dynamoObj.M = dynamoMapObj;

} else if (type.name === 'list') {

if (!Array.isArray(val)) {
Expand Down
41 changes: 41 additions & 0 deletions test/Schema.js
Expand Up @@ -987,6 +987,47 @@ describe('Schema tests', function (){
});
});

it('Parses document types to DynamoDB with nested maps within maps when saveUnknown=true and useDocumentTypes=true', async function () {

var schema = new Schema({
id: Number,
anotherMap: Map,
}, {
saveUnknown: true
});

var model = {
id: 2,
anotherMap: {
test1: {
name: 'Bob'
},
test2: {
name: 'Smith'
}
}
};
const result = await schema.toDynamo(model);

result.should.eql({
id: { N: '2' },
anotherMap: {
M: {
test1: {
M: {
name: { S: 'Bob' },
}
},
test2: {
M: {
name: { S: 'Smith' },
}
}
}
}
});
});

it('Handle unknown attributes in DynamoDB', async function () {

var unknownSchema = new Schema({
Expand Down

0 comments on commit 873a6ed

Please sign in to comment.