forked from dynamoose/dynamoose
/
Schema.js
336 lines (283 loc) · 9.43 KB
/
Schema.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
'use strict';
const Attribute = require('./Attribute');
const errors = require('./errors');
const VirtualType = require('./VirtualType');
// const util = require('util');
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 || {};
if (this.options.throughput) {
let {throughput} = this.options;
if (typeof throughput === 'number') {
throughput = {'read': throughput, 'write': throughput};
}
this.throughput = throughput;
} else {
this.throughput = {'read': 1, 'write': 1};
}
if ((!this.throughput.read || !this.throughput.write) &&
this.throughput.read >= 1 && this.throughput.write >= 1) {
throw new errors.SchemaError(`Invalid throughput: ${this.throughput}`);
}
/*
* Added support for timestamps attribute
*/
if (this.options.timestamps) {
let createdAt = null;
let updatedAt = null;
if (this.options.timestamps === true) {
createdAt = 'createdAt';
updatedAt = 'updatedAt';
} else if (typeof this.options.timestamps === 'object') {
if (this.options.timestamps.createdAt && this.options.timestamps.updatedAt) {
({createdAt, updatedAt} = this.options.timestamps);
} else {
throw new errors.SchemaError('Missing createdAt and updatedAt timestamps attribute. Maybe set timestamps: true?');
}
} else {
throw new errors.SchemaError(`Invalid syntax for timestamp: ${this.options.timestamps}`);
}
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(); };
this.timestamps = {createdAt, updatedAt};
}
/*
* Added support for expires attribute
*/
if (this.options.expires !== null && this.options.expires !== undefined) {
const expires = {
'attribute': 'expires',
'returnExpiredItems': true
};
if (typeof this.options.expires === 'number') {
expires.ttl = this.options.expires;
} else if (typeof this.options.expires === 'object') {
if (typeof this.options.expires.ttl === 'number') {
expires.ttl = this.options.expires.ttl;
} else {
throw new errors.SchemaError('Missing or invalided ttl for expires attribute.');
}
if (typeof this.options.expires.attribute === 'string') {
expires.attribute = this.options.expires.attribute;
}
if (typeof this.options.expires.returnExpiredItems === 'boolean') {
expires.returnExpiredItems = this.options.expires.returnExpiredItems;
}
if (typeof this.options.expires.defaultExpires === 'function') {
expires.defaultExpires = this.options.expires.defaultExpires;
}
} else {
throw new errors.SchemaError(`Invalid syntax for expires: ${this.options.expires}`);
}
const defaultExpires = function () {
return new Date(Date.now() + expires.ttl * 1000);
};
obj[expires.attribute] = {
'type': Number,
'default': expires.defaultExpires || defaultExpires,
'set' (v) {
return Math.floor(v.getTime() / 1000);
},
'get' (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) {
const dynamoObj = {};
let attr, name;
for (name in model) {
if (Object.prototype.hasOwnProperty.call(model, name)) {
if (model[name] === undefined || model[name] === null || Number.isNaN(model[name])) {
debug('toDynamo: skipping attribute: %s because its definition or value is null, undefined, or NaN', name);
continue;
}
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]);
this.attributes[name] = attr;
}
}
}
for (name in this.attributes) {
attr = this.attributes[name];
await attr.setDefault(model);
let dynamoAttr;
if (this.attributeToDynamo) {
dynamoAttr = await this.attributeToDynamo(name, model[name], model, attr.toDynamo.bind(attr), options);
} else {
dynamoAttr = await attr.toDynamo(model[name], undefined, model, options);
}
if (dynamoAttr) {
dynamoObj[attr.name] = dynamoAttr;
}
}
debug('toDynamo: %s', dynamoObj);
return dynamoObj;
};
Schema.prototype.parseDynamo = async function (model, dynamoObj) {
for (const name in dynamoObj) {
let attr = this.attributes[name];
if (!attr && this.options.errorUnknown) {
const hashKey = this.hashKey && this.hashKey.name && dynamoObj[this.hashKey.name] && JSON.stringify(dynamoObj[this.hashKey.name]);
const rangeKey = this.rangeKey && this.rangeKey.name && JSON.stringify(dynamoObj[this.rangeKey.name]);
let errorMessage = `Unknown top-level attribute ${name} on model ${model.$__.name} with `;
if (hashKey) { errorMessage += `hash-key ${hashKey} and `; }
if (rangeKey) { errorMessage += `range-key ${rangeKey} and `; }
errorMessage += `value: ${JSON.stringify(dynamoObj[name])}`;
throw new errors.ParseError(errorMessage);
}
if (!attr && this.options.saveUnknown === true || Array.isArray(this.options.saveUnknown) && this.options.saveUnknown.indexOf(name) >= 0) {
attr = Attribute.createUnknownAttributeFromDynamo(this, name, dynamoObj[name]);
this.attributes[name] = attr;
}
if (attr) {
let attrVal;
if (this.attributeFromDynamo) {
attrVal = await this.attributeFromDynamo(name, dynamoObj[name], attr.parseDynamo.bind(attr), model);
} else {
attrVal = await attr.parseDynamo(dynamoObj[name]);
}
if (attrVal !== undefined && attrVal !== null) {
model[name] = attrVal;
}
} else {
debug('parseDynamo: received an attribute name (%s) that is not defined in the schema', name);
}
}
if (model.$__) {
model.$__.originalItem = JSON.parse(JSON.stringify(model));
}
debug('parseDynamo: %s', model);
return dynamoObj;
};
/**
* Adds an instance method to documents constructed from Models compiled from this schema.
*
* ####Example
*
* let schema = kittySchema = new Schema(..);
*
* schema.method('meow', function () {
* console.log('meeeeeoooooooooooow');
* })
*
* let Kitty = mongoose.model('Kitty', schema);
*
* let fizz = new Kitty;
* fizz.meow(); // meeeeeooooooooooooow
*
* If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
*
* schema.method({
* purr: function () {}
* , scratch: function () {}
* });
*
* // later
* fizz.purr();
* fizz.scratch();
*
* @param {String|Object} method name
* @param {Function} [fn]
* @api public
*/
Schema.prototype.method = function (name, fn) {
if (typeof name === 'string') {
this.methods[name] = fn;
} else {
for (const i in name) {
this.methods[i] = name[i];
}
}
return this;
};
/**
* Adds static "class" methods to Models compiled from this schema.
*
* ####Example
*
* let schema = new Schema(..);
* schema.static('findByName', function (name, callback) {
* return this.find({ name: name }, callback);
* });
*
* let Drink = mongoose.model('Drink', schema);
* Drink.findByName('sanpellegrino', function (err, drinks) {
* //
* });
*
* If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
*
* @param {String} name
* @param {Function} fn
* @api public
*/
Schema.prototype.static = function (name, fn) {
if (typeof name === 'string') {
this.statics[name] = fn;
} else {
for (const i in name) {
this.statics[i] = name[i];
}
}
return this;
};
/**
* Creates a virtual type with the given name.
*
* @param {String} name
* @param {Object} [options]
* @return {VirtualType}
*/
Schema.prototype.virtual = function (name, options) {
// let virtuals = this.virtuals;
const parts = name.split('.');
this.virtuals[name] = parts.reduce((mem, part, i) => {
if (mem[part]) {
return mem[part];
}
mem[part] = i === parts.length - 1 ? new VirtualType(options, name) : {};
return mem[part];
}, this.tree);
return this.virtuals[name];
};
/**
* Returns the virtual type with the given `name`.
*
* @param {String} name
* @return {VirtualType}
*/
Schema.prototype.virtualpath = function (name) {
return this.virtuals[name];
};
module.exports = Schema;