type-arango
Version:
ArangoDB Foxx decorators and utilities for TypeScript
214 lines • 8.22 kB
JavaScript
"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Entity = void 0;
var _1 = require(".");
var errors_1 = require("../errors");
var utils_1 = require("../utils");
// const nativeKeys = ['constructor','toString']
var unenumerable = ['_saveKeys', '_collection', '_relations'];
var globalAttributes = ['_key', '_rev', '_id', '_oldRev'];
var accessibleKeys = globalAttributes.concat('_saveKeys');
var Entity = /** @class */ (function () {
function Entity(doc, isSync) {
var _this = this;
if (isSync === void 0) { isSync = false; }
this._saveKeys = [];
if (typeof doc === 'string')
doc = { _key: doc };
if (doc) {
if (!isSync)
this._saveKeys = Object.keys(doc).filter(function (k) { return _this[k] !== doc[k]; });
this.merge(doc);
}
var _doc = this._doc;
var constructor = this.constructor;
var attribute = _doc.attribute;
var keys = Object.keys(attribute).concat(accessibleKeys);
this._collection = utils_1.isFoxx() ? _doc.col.db : {};
// hide some attrs
unenumerable.forEach(function (attr) { return Object.defineProperty(_this, attr, { enumerable: false }); });
if (!utils_1.isFoxx())
return this;
// setup proxy
return new Proxy(this, {
// get(target: any, key: string){
// if(nativeKeys.includes(key)) return target[key]
//
// // const cleanKey = key.startsWith('_') ? key.substr(1) : key
//
// // // return relation values as entity._attribute
// // if(key.startsWith('_') && _doc.relation[cleanKey]){
// // return target[cleanKey]
// // }
// //
// // // support relation entity load via entity.relation()
// // if(_doc.relation[key]) return _doc.resolveRelation.bind(_doc, target, key)
//
// return target[key]
// },
set: function (target, key, val) {
if (typeof key === 'symbol')
throw new errors_1.SymbolKeysNotSupportedError();
if (_doc.relation[key]) {
target._saveKeys.push(key);
target[key] = val;
return true;
}
// check key
else if (!keys.includes(String(key))) {
throw new errors_1.AttributeNotInEntityError(constructor.name, key);
}
// joi validation
else if (attribute[key]) {
var _a = attribute[key].schema.validate(val), error = _a.error, value = _a.value;
if (error)
throw error;
val = value;
}
if (target[key] === val)
return true;
// set
target._saveKeys.push(key);
target[key] = val;
return true;
}
});
}
Object.defineProperty(Entity, "_doc", {
get: function () {
return _1.getDocumentForContainer(this);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Entity, "_db", {
get: function () {
return utils_1.db;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Entity.prototype, "_doc", {
get: function () {
return this.constructor._doc;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Entity, "_relations", {
get: function () {
return Object.keys(this._doc.relation);
},
enumerable: false,
configurable: true
});
/**
* Returns related entity
*/
Entity.prototype.related = function (attribute, attributes) {
if (!this._doc.relation[attribute])
throw new errors_1.AttributeIsNotARelationError(this.name, attribute);
return this._doc.resolveRelation(this, attribute, attributes);
};
/**
* Creates the document by using .save({update:false})
*/
Entity.prototype.insert = function () {
return this.save({ update: false });
};
/**
* Alias for insert
* @deprecated
*/
Entity.prototype.create = function () {
console.warn('Using entity.create is deprecated, use entity.insert instead');
return this.insert();
};
/**
* Merges `obj` into `this`
*/
Entity.prototype.merge = function () {
var obj = [];
for (var _i = 0; _i < arguments.length; _i++) {
obj[_i] = arguments[_i];
}
return Object.assign.apply(Object, __spreadArrays([this], obj));
};
/**
* Converts entity to object (strips property listeners)
*/
Entity.prototype.toObject = function () {
return Object.assign({}, this);
};
/**
* Saves changed attributes to database. Creates a new document when no _key is available.
* Use the option {update:false} to always create a new document even when a _key is provided.
*/
Entity.prototype.save = function (options) {
var _this = this;
if (options === void 0) { options = {}; }
var _a = this, _saveKeys = _a._saveKeys, _key = _a._key, _doc = _a._doc, _collection = _a._collection;
if (options.update === undefined)
options.update = true;
if (!_saveKeys.length)
return this;
// accumulate changed values from _saveKeys into object
var data = _saveKeys.reduce(function (o, key) {
var v = _this[key];
var relation = _doc.relation[key];
if (relation) {
// save assigned entity
if (v instanceof Entity && v._saveKeys.length)
v.save();
o[key] = v instanceof Entity ? v._key : v;
}
else
o[key] = v;
return o;
}, {});
var res;
// insert / update
if (options.update && _key) {
data = _doc.emitBefore('update', data);
res = _doc.emitAfter('insert', _collection.update({ _key: _key }, data, options));
}
else {
data = _doc.emitBefore('insert', data);
res = _doc.emitAfter('insert', _collection.insert(data, Object.assign(options, { returnNew: true })).new);
}
this.merge(res);
// reset
this._saveKeys = [];
return this;
};
/**
* Replaces the document with the provided doc, ignoring _saveKeys
*/
Entity.prototype.replace = function (doc, options) {
var _a = this, _key = _a._key, _doc = _a._doc, _collection = _a._collection;
if (!_key)
throw new errors_1.MissingKeyError(this.constructor.name);
doc = _doc.emitBefore('replace', doc);
return this.merge(_doc.emitAfter('insert', _collection.replace({ _key: _key }, doc, options)));
};
/**
* Removes the document
*/
Entity.prototype.remove = function (options) {
var _a = this, _key = _a._key, _doc = _a._doc, _collection = _a._collection;
if (!_key)
throw new errors_1.MissingKeyError(this.constructor.name);
_doc.emitBefore('remove', _key);
return this.merge(_doc.emitAfter('remove', _collection.remove({ _key: _key }, options)));
};
return Entity;
}());
exports.Entity = Entity;
//# sourceMappingURL=Entity.model.js.map