|
|
|
@ -11,17 +11,21 @@ var dateToJSON = function () { return { $$date: this.getTime() }; } |
|
|
|
|
* Serialize an object to be persisted to a one-line string |
|
|
|
|
* Accepted primitive types: Number, String, Boolean, Date, null |
|
|
|
|
* Accepted secondary types: Objects, Arrays |
|
|
|
|
* TODO: throw an error if variable name begins with '$' |
|
|
|
|
*/ |
|
|
|
|
function serialize (obj) { |
|
|
|
|
var res; |
|
|
|
|
|
|
|
|
|
// Keep track of the fact this is a Date object
|
|
|
|
|
// Keep track of the fact that this is a Date object
|
|
|
|
|
Date.prototype.toJSON = dateToJSON; |
|
|
|
|
|
|
|
|
|
res = JSON.stringify(obj, function (k, v) { |
|
|
|
|
// Non-treatable edge case here: if part of the object if of the form { $$date: number }
|
|
|
|
|
// Its serialized-then-deserialized version it will transformed into a Date object
|
|
|
|
|
// But you really need to want it to trigger such behaviour, even when warned not to use '$' at the beginning of the field names...
|
|
|
|
|
if (k[0] === '$' && !(k === '$$date' && typeof v === 'number')) { throw 'Keys cannot begin with the $ character'; } |
|
|
|
|
|
|
|
|
|
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null) { return v; } |
|
|
|
|
if (v && v.constructor && v.constructor.name === 'Date') { return { $$date: v.toString() }; } |
|
|
|
|
//if (v && v.constructor && v.constructor.name === 'Date') { console.log("==============="); return { $$date: v.toString() }; }
|
|
|
|
|
|
|
|
|
|
return v; |
|
|
|
|
}); |
|
|
|
@ -80,8 +84,19 @@ function deepCopy (obj) { |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* Modify a DB object according to an update query |
|
|
|
|
* For now the updateQuery only replaces the object |
|
|
|
|
*/ |
|
|
|
|
function modify (obj, updateQuery) { |
|
|
|
|
updateQuery = deepCopy(updateQuery); |
|
|
|
|
updateQuery._id = obj._id; |
|
|
|
|
return updateQuery; |
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Interface
|
|
|
|
|
module.exports.serialize = serialize; |
|
|
|
|
module.exports.deserialize = deserialize; |
|
|
|
|
module.exports.deepCopy = deepCopy; |
|
|
|
|
module.exports.modify = modify; |
|
|
|
|