octonom
Version:
Object Document Mapper for any database
76 lines • 3.12 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("../errors");
const schema_1 = require("./schema");
class ReferenceSchema {
constructor(options) {
this.options = options;
}
create(value, sanitizeOptions = {}) {
const sanitizedValue = this.sanitize(value, sanitizeOptions);
if (sanitizedValue === undefined) {
return undefined;
}
const idField = this.options.collection().modelIdField;
const id = typeof sanitizedValue === 'string'
? sanitizedValue
: sanitizedValue[idField];
if (id === undefined) {
throw new errors_1.SanitizationError('Reference id is undefined.', 'no-id', sanitizeOptions.parent);
}
const instance = {
value: sanitizedValue,
id,
schema: this,
};
return instance;
}
populate(instance, populateReference) {
return __awaiter(this, void 0, void 0, function* () {
const modelInstance = yield this.options.collection().findById(instance.id);
if (populateReference !== true) {
yield modelInstance.populate(populateReference);
}
instance.value = modelInstance;
return instance.value;
});
}
toObject(instance, options = {}) {
if (options.unpopulate) {
return instance.id;
}
if (typeof instance.value === 'string') {
return instance.value;
}
return instance.value.toObject(options);
}
validate(instance) {
return __awaiter(this, void 0, void 0, function* () {
yield schema_1.validate(this.options, instance);
});
}
sanitize(value, sanitizeOptions = {}) {
if (value === undefined || typeof value === 'string') {
return value;
}
// If it's not an id we expect a model. We don't instantiate from
// a plain object because an object coming from a database will only
// contain the id and if it has been populated it will already be a model.
const model = this.options.collection().model;
if (!(value instanceof model)) {
throw new errors_1.SanitizationError('Value is not an instance or an id.');
}
// clone model instance
return new model(value, sanitizeOptions);
}
}
exports.ReferenceSchema = ReferenceSchema;
//# sourceMappingURL=reference.js.map