Skip to content

Commit

Permalink
fix(schema): fix handling schema updates in constructor call
Browse files Browse the repository at this point in the history
this fixes how schema options can be defined and updated

fix dynamoose#323
  • Loading branch information
hammywhammy committed Feb 12, 2019
1 parent 0ef6d87 commit 001ca2c
Show file tree
Hide file tree
Showing 6 changed files with 2,281 additions and 2,251 deletions.
27 changes: 0 additions & 27 deletions issue_reproduction/323/index.js

This file was deleted.

69 changes: 50 additions & 19 deletions issue_reproduction/323/model.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
const {
initialize
} = require('./index')
const shortId = require('shortid');
const dynamoose = require('../../lib');
const dynalite = require('dynalite');

let serverRef

const startUpAndReturnDynamo = async () => {
const dynaliteServer = dynalite();
await dynaliteServer.listen(8000);
serverRef = dynaliteServer;
};

const createDynamooseInstance = () => {
dynamoose.AWS.config.update({
accessKeyId: 'AKID',
secretAccessKey: 'SECRET',
region: 'us-east-1'
});
dynamoose.local(); // This defaults to "http://localhost:8000"
return dynamoose
}

const initialize = async () => {
await startUpAndReturnDynamo()
return createDynamooseInstance()
}

const buildModel = async () => {
let dynamooseRef = await initialize()
Expand Down Expand Up @@ -53,22 +75,31 @@ const buildModel = async () => {
}
});

try {
const adUrlModel = new Model({
title: '123',
type: 'cats',
userId: 123,
customerId: 123,
campaignId: 123,
mobile: {
"123" : '123'
}
});
const results = await adUrlModel.save();
console.log(JSON.stringify(results, null, 2))
} catch(e) {

}
const adUrlModel = new Model({
title: '123',
type: 'cats',
userId: 123,
customerId: 123,
campaignId: 123,
mobile: {
"123" : '123'
}
});
const results = await adUrlModel.save();
console.log(JSON.stringify(results, null, 2))
await Model.create({
title: '1234',
type: 'cats4',
userId: 1234,
customerId: 1234,
campaignId: 1234,
mobile: {
"1234" : '1234'
}
})
let allModels = await Model.scan({}).exec()
console.log(JSON.stringify(allModels, null, 2))
await serverRef.close()
}

buildModel()
11 changes: 7 additions & 4 deletions lib/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ Model.compile = function compile (name, schema, options, base) {
function NewModel (obj) {
Model.call(this, obj);
applyVirtuals(this, schema);
mergeSchemaOptions(schema, options);
this.$__.originalItem = obj;
}

Expand Down Expand Up @@ -377,6 +378,12 @@ const applyVirtuals = function(model, schema){
}
};


const mergeSchemaOptions = function(schema, options = {}){
debug('applying option merge');
schema.addAndParseOptions(options, true);
};

function validKeyValue(value) {
return value !== undefined && value !== null && value !== '';
}
Expand Down Expand Up @@ -473,10 +480,6 @@ Model.prototype.put = async function(options, next) {
toDynamoOptions.updateExpires = true;
}

if (this.$__.options.saveUnknown) {
toDynamoOptions.saveUnknown = this.$__.options.saveUnknown;
}

let schema = this.$__.schema;
item = {
TableName: this.$__.name,
Expand Down
91 changes: 50 additions & 41 deletions lib/Schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,39 @@ const debug = require('debug')('dynamoose:schema');

function Schema(obj, options) {
debug('Creating Schema', obj);

this.tree = {};
this.methods = {};
this.statics = {};
this.virtuals = {};
this.options = options || {};
this.addAndParseOptions(options, false, obj);

this.attributes = {};
this.indexes = {local: {}, global: {}};

for(const n in obj) {

if(this.attributes[n]) {
throw new errors.SchemaError(`Duplicate attribute: ${n}`);
}

debug('Adding Attribute to Schema (%s)', n, obj);
this.attributes[n] = Attribute.create(this, n, obj[n]);
}
}

/*Schema.prototype.attribute = function(name, obj) {
debug('Adding Attribute to Schema (%s)', name, obj);
this Attribute.create(name, obj);
};*/

Schema.prototype.addAndParseOptions = function (options, isMerge, obj) {
if (!isMerge) {
this.options = options || {};
} else {
this.options = {...this.options, ...options};
}
if(this.options.throughput) {
let throughput = this.options.throughput;
if(typeof throughput === 'number') {
Expand Down Expand Up @@ -53,15 +79,17 @@ function Schema(obj, options) {
throw new errors.SchemaError(`Invalid syntax for timestamp: ${this.options.timestamps}`);
}

obj[createdAt] = obj[createdAt] || {};
obj[createdAt].type = Date;
obj[createdAt].default = Date.now;
if (!isMerge) {
obj[createdAt] = obj[createdAt] || {};
obj[createdAt].type = Date;
obj[createdAt].default = Date.now;


obj[updatedAt] = obj[updatedAt] || {};
obj[updatedAt].type = Date;
obj[updatedAt].default = Date.now;
obj[updatedAt].set = function() { return Date.now(); };
obj[updatedAt] = obj[updatedAt] || {};
obj[updatedAt].type = Date;
obj[updatedAt].default = Date.now;
obj[updatedAt].set = function() { return Date.now(); };
}
this.timestamps = { createdAt: createdAt, updatedAt: updatedAt };
}

Expand Down Expand Up @@ -102,43 +130,25 @@ function Schema(obj, options) {
return new Date(Date.now() + (expires.ttl * 1000));
};

obj[expires.attribute] = {
type: Number,
default: expires.defaultExpires || defaultExpires,
set: function(v) {
return Math.floor(v.getTime() / 1000);
},
get: function (v) {
return new Date(v * 1000);
}
};
if (!isMerge) {
obj[expires.attribute] = {
type: Number,
default: expires.defaultExpires || defaultExpires,
set: function(v) {
return Math.floor(v.getTime() / 1000);
},
get: function (v) {
return new Date(v * 1000);
}
};
}
this.expires = expires;
}
this.useDocumentTypes = this.options.useDocumentTypes === undefined ? true : this.options.useDocumentTypes;
this.useNativeBooleans = this.options.useNativeBooleans === undefined ? true : this.options.useNativeBooleans;
this.attributeFromDynamo = this.options.attributeFromDynamo;
this.attributeToDynamo = this.options.attributeToDynamo;

this.attributes = {};
this.indexes = {local: {}, global: {}};

for(const n in obj) {

if(this.attributes[n]) {
throw new errors.SchemaError(`Duplicate attribute: ${n}`);
}

debug('Adding Attribute to Schema (%s)', n, obj);
this.attributes[n] = Attribute.create(this, n, obj[n]);
}
}

/*Schema.prototype.attribute = function(name, obj) {
debug('Adding Attribute to Schema (%s)', name, obj);
this Attribute.create(name, obj);
};*/
};

Schema.prototype.toDynamo = async function(model, options) {

Expand All @@ -153,7 +163,6 @@ Schema.prototype.toDynamo = async function(model, options) {
debug('toDynamo: skipping attribute: %s because its definition or value is null, undefined, or NaN', name);
continue;
}
debugger
attr = this.attributes[name];
if((!attr && this.options.saveUnknown === true) || (Array.isArray(this.options.saveUnknown) && this.options.saveUnknown.indexOf(name) >= 0)) {
attr = Attribute.create(this, name, model[name]);
Expand Down
Loading

0 comments on commit 001ca2c

Please sign in to comment.