@starrah/mongo-ts-struct
Version:
Mongoose wrapper for Typescript supports
63 lines • 3.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose = require("mongoose");
const helpers_1 = require("../../helpers");
const errors_1 = require("../../errors");
function toSchema(TypedSchemaClass) {
const $metadata = helpers_1.MetadataAgent.getMeta(TypedSchemaClass);
// detect if the TypedSchemaClass definition was decorated with @TypedSchema
const schemaClassName = TypedSchemaClass.name;
if (!$metadata || !$metadata[`isProcessed:${schemaClassName}`]) {
throw new errors_1.TypedSchemaDecoratorMissingError();
}
// try to cache schema object if exists, in a case where toSchema was already called of this class
if (helpers_1.MetadataAgent.has(TypedSchemaClass, 'processedSchemaObject')) {
// -- hook 03
/** OnSchemaCached Stage **/
const cachedSchema = $metadata['processedSchemaObject'];
if (typeof TypedSchemaClass.prototype['onSchemaCached'] == 'function') {
TypedSchemaClass.prototype['onSchemaCached'](cachedSchema);
}
return cachedSchema;
}
// if this is the first time calling toSchema
const { functions, schemaDefinitions, schemaConfig } = $metadata;
if (!schemaDefinitions) {
throw new errors_1.EmptyTypedSchemaClassError();
}
if (functions && (!functions.statics && !functions.methods)) { /* throw Error */ }
const config = schemaConfig ? schemaConfig.options : undefined;
// -- hook 01
/** OnConstructDefinitions Stage **/
if (typeof TypedSchemaClass.prototype['onConstructDefinitions'] == 'function') {
TypedSchemaClass.prototype['onConstructDefinitions'](schemaDefinitions, functions);
}
// create the mongoose scheme object.
const schema = new mongoose.Schema(schemaDefinitions, config);
// -- hook 02
/** OnSchemaCreated Stage **/
if (typeof TypedSchemaClass.prototype['onSchemaCreated'] == 'function') {
TypedSchemaClass.prototype['onSchemaCreated'](schema);
}
// assign class method to the schema.
const boundSchema = assignSchemaFunctions(schema, functions);
if (typeof TypedSchemaClass.prototype['onSchemaBound'] == 'function') {
TypedSchemaClass.prototype['onSchemaBound'](schema);
}
// set the processed schema object for caching - any future calling of this function.
helpers_1.MetadataAgent.set(TypedSchemaClass, ['processedSchemaObject', boundSchema]);
return boundSchema;
}
exports.toSchema = toSchema;
function assignSchemaFunctions(schema, functions = {}) {
if (functions) {
functions.methods ?
Object.keys(functions.methods).forEach(name => schema.method(name, functions.methods[name])) :
undefined;
functions.statics ?
Object.keys(functions.statics).forEach(name => schema.static(name, functions.statics[name])) :
undefined;
}
return schema;
}
//# sourceMappingURL=to-schema.js.map