Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@yued/typegoose

Package Overview
Dependencies
Maintainers
4
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@yued/typegoose - npm Package Compare versions

Comparing version
5.4.1
to
5.4.2
+12
lib/data.d.ts
export declare const methods: {
staticMethods: {};
instanceMethods: {};
};
export declare const schema: {};
export declare const models: {};
export declare const virtuals: {};
export declare const hooks: {};
export declare const plugins: {};
export declare const constructors: {
[key: string]: Function;
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.methods = { staticMethods: {}, instanceMethods: {} };
exports.schema = {};
exports.models = {};
exports.virtuals = {};
exports.hooks = {};
exports.plugins = {};
// tslint:disable-next-line:ban-types
exports.constructors = {};
//# sourceMappingURL=data.js.map
export declare class InvalidPropError extends Error {
constructor(typeName: any, key: string);
}
export declare class NotNumberTypeError extends Error {
constructor(key: string);
}
export declare class NotStringTypeError extends Error {
constructor(key: string);
}
export declare class NoMetadataError extends Error {
constructor(key: string);
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class InvalidPropError extends Error {
constructor(typeName, key) {
super(`In property ${key}: ${typeName} is not a primitive type nor a Typegoose schema (Not extending it).`);
}
}
exports.InvalidPropError = InvalidPropError;
class NotNumberTypeError extends Error {
constructor(key) {
super(`Type of ${key} property is not a number.`);
}
}
exports.NotNumberTypeError = NotNumberTypeError;
class NotStringTypeError extends Error {
constructor(key) {
super(`Type of ${key} property is not a string.`);
}
}
exports.NotStringTypeError = NotStringTypeError;
class NoMetadataError extends Error {
constructor(key) {
super(`There is no metadata for the "${key}" property. ` +
'Check if emitDecoratorMetadata is enabled in tsconfig.json ' +
'or check if you\'ve declared a sub document\'s class after usage.');
}
}
exports.NoMetadataError = NoMetadataError;
//# sourceMappingURL=errors.js.map
import { MongooseDocument } from 'mongoose';
declare type DocumentMethod = 'init' | 'validate' | 'save' | 'remove';
declare type ClassDecorator = (constructor: any) => void;
declare type HookNextFn = (err?: Error) => void;
declare type PreDoneFn = () => void;
declare type TypegooseDoc<T> = T & MongooseDocument;
declare type DocumentPreSerialFn<T> = (this: TypegooseDoc<T>, next: HookNextFn) => void;
declare type DocumentPreParallelFn<T> = (this: TypegooseDoc<T>, next: HookNextFn, done: PreDoneFn) => void;
declare type SimplePreSerialFn<T> = (next: HookNextFn) => void;
declare type SimplePreParallelFn<T> = (next: HookNextFn, done: PreDoneFn) => void;
declare type ModelPostFn<T> = (result: any, next?: HookNextFn) => void;
declare type PostNumberResponse<T> = (result: number, next?: HookNextFn) => void;
declare type PostSingleResponse<T> = (result: TypegooseDoc<T>, next?: HookNextFn) => void;
declare type PostMultipleResponse<T> = (result: TypegooseDoc<T>[], next?: HookNextFn) => void;
declare type PostNumberWithError<T> = (error: Error, result: number, next: HookNextFn) => void;
declare type PostSingleWithError<T> = (error: Error, result: TypegooseDoc<T>, next: HookNextFn) => void;
declare type PostMultipleWithError<T> = (error: Error, result: TypegooseDoc<T>[], net: HookNextFn) => void;
declare type SingleMethod = 'findOne' | 'findOneAndRemove' | 'findOneAndUpdate' | DocumentMethod;
declare type MultipleMethod = 'find' | 'update';
export declare const pre: {
<T>(method: "init" | "validate" | "save" | "remove", fn: DocumentPreSerialFn<T>): ClassDecorator;
<T>(method: "init" | "validate" | "save" | "remove", parallel: boolean, fn: DocumentPreParallelFn<T>): ClassDecorator;
<T>(method: "count" | "find" | "findOne" | "findOneAndRemove" | "findOneAndUpdate" | "update" | "insertMany" | "updateOne" | "updateMany", fn: SimplePreSerialFn<T>): ClassDecorator;
<T>(method: "count" | "find" | "findOne" | "findOneAndRemove" | "findOneAndUpdate" | "update" | "insertMany" | "updateOne" | "updateMany", parallel: boolean, fn: SimplePreParallelFn<T>): ClassDecorator;
};
export declare const post: {
<T>(method: "count", fn: PostNumberResponse<T>): ClassDecorator;
<T>(method: "count", fn: PostNumberWithError<T>): ClassDecorator;
<T>(method: SingleMethod, fn: PostSingleResponse<T>): ClassDecorator;
<T>(method: SingleMethod, fn: PostSingleWithError<T>): ClassDecorator;
<T>(method: MultipleMethod, fn: PostMultipleResponse<T>): ClassDecorator;
<T>(method: MultipleMethod, fn: PostMultipleWithError<T>): ClassDecorator;
<T>(method: "insertMany", fn: ModelPostFn<T> | PostMultipleResponse<T>): ClassDecorator;
};
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const data_1 = require("./data");
const hooks = {
pre(...args) {
return (constructor) => {
addToHooks(constructor.name, 'pre', args);
};
},
post(...args) {
return (constructor) => {
addToHooks(constructor.name, 'post', args);
};
},
};
const addToHooks = (name, hookType, args) => {
if (!data_1.hooks[name]) {
data_1.hooks[name] = { pre: [], post: [] };
}
data_1.hooks[name][hookType].push(args);
};
exports.pre = hooks.pre;
exports.post = hooks.post;
//# sourceMappingURL=hooks.js.map
/**
* copy-paste from mongodb package (should be same as IndexOptions from 'mongodb')
*/
export interface IndexOptions {
/**
* Mongoose-specific syntactic sugar, uses ms to convert
* expires option into seconds for the expireAfterSeconds in the above link.
*/
expires?: string;
/**
* Creates an unique index.
*/
unique?: boolean;
/**
* Creates a sparse index.
*/
sparse?: boolean;
/**
* Creates the index in the background, yielding whenever possible.
*/
background?: boolean;
/**
* A unique index cannot be created on a key that has pre-existing duplicate values.
* If you would like to create the index anyway, keeping the first document the database indexes and
* deleting all subsequent documents that have duplicate value
*/
dropDups?: boolean;
/**
* For geo spatial indexes set the lower bound for the co-ordinates.
*/
min?: number;
/**
* For geo spatial indexes set the high bound for the co-ordinates.
*/
max?: number;
/**
* Specify the format version of the indexes.
*/
v?: number;
/**
* Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
*/
expireAfterSeconds?: number;
/**
* Override the auto generated index name (useful if the resulting name is larger than 128 bytes)
*/
name?: string;
/**
* Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
*/
partialFilterExpression?: any;
collation?: object;
default_language?: string;
}
/**
* Defines an index (most likely compound) for this schema.
* @param options Options to pass to MongoDB driver's createIndex() function
*/
export declare const index: (fields: any, options?: IndexOptions) => (constructor: any) => void;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Defines an index (most likely compound) for this schema.
* @param options Options to pass to MongoDB driver's createIndex() function
*/
exports.index = (fields, options) => {
return (constructor) => {
const indices = Reflect.getMetadata('typegoose:indices', constructor) || [];
indices.push({ fields, options });
Reflect.defineMetadata('typegoose:indices', indices, constructor);
};
};
//# sourceMappingURL=index.js.map
export declare const staticMethod: (target: any, key: string, descriptor: TypedPropertyDescriptor<any>) => void;
export declare const instanceMethod: (target: any, key: string, descriptor: TypedPropertyDescriptor<any>) => void;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const data_1 = require("./data");
const baseMethod = (target, key, descriptor, methodType) => {
if (descriptor === undefined) {
descriptor = Object.getOwnPropertyDescriptor(target, key);
}
let name;
if (methodType === 'instanceMethods') {
name = target.constructor.name;
}
if (methodType === 'staticMethods') {
name = target.name;
}
if (!data_1.methods[methodType][name]) {
data_1.methods[methodType][name] = {};
}
const method = descriptor.value;
data_1.methods[methodType][name] = Object.assign({}, data_1.methods[methodType][name], { [key]: method });
};
exports.staticMethod = (target, key, descriptor) => baseMethod(target, key, descriptor, 'staticMethods');
exports.instanceMethod = (target, key, descriptor) => baseMethod(target, key, descriptor, 'instanceMethods');
//# sourceMappingURL=method.js.map
export declare const plugin: (mongoosePlugin: any, options?: any) => (constructor: any) => void;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const data_1 = require("./data");
exports.plugin = (mongoosePlugin, options) => (constructor) => {
const name = constructor.name;
if (!data_1.plugins[name]) {
data_1.plugins[name] = [];
}
data_1.plugins[name].push({ mongoosePlugin, options });
};
//# sourceMappingURL=plugin.js.map
import { ObjectID } from 'bson';
export declare type Func = (...args: any[]) => any;
export declare type RequiredType = boolean | [boolean, string] | string | Func | [Func, string];
export declare type ValidatorFunction = (value: any) => boolean | Promise<boolean>;
export declare type Validator = ValidatorFunction | RegExp | {
validator: ValidatorFunction;
message?: string;
};
export interface BasePropOptions {
required?: RequiredType;
enum?: string[] | object;
default?: any;
validate?: Validator | Validator[];
unique?: boolean;
index?: boolean;
sparse?: boolean;
expires?: string | number;
_id?: boolean;
}
export interface PropOptions extends BasePropOptions {
ref?: any;
}
export interface ValidateNumberOptions {
min?: number | [number, string];
max?: number | [number, string];
}
export interface ValidateStringOptions {
minlength?: number | [number, string];
maxlength?: number | [number, string];
match?: RegExp | [RegExp, string];
}
export declare type PropOptionsWithNumberValidate = PropOptions & ValidateNumberOptions;
export declare type PropOptionsWithStringValidate = PropOptions & ValidateStringOptions;
export declare type PropOptionsWithValidate = PropOptionsWithNumberValidate | PropOptionsWithStringValidate;
export declare const prop: (options?: PropOptionsWithValidate) => (target: any, key: string) => void;
export interface ArrayPropOptions extends BasePropOptions {
items?: any;
itemsRef?: any;
}
export declare const arrayProp: (options: ArrayPropOptions) => (target: any, key: string) => void;
export declare type Ref<T> = T | ObjectID;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose = require("mongoose");
const _ = require("lodash");
const data_1 = require("./data");
const utils_1 = require("./utils");
const errors_1 = require("./errors");
const isWithStringValidate = (options) => (options.minlength || options.maxlength || options.match);
const isWithNumberValidate = (options) => (options.min || options.max);
const baseProp = (rawOptions, Type, target, key, isArray = false) => {
const name = target.constructor.name;
const isGetterSetter = Object.getOwnPropertyDescriptor(target, key);
if (isGetterSetter) {
if (isGetterSetter.get) {
if (!data_1.virtuals[name]) {
data_1.virtuals[name] = {};
}
if (!data_1.virtuals[name][key]) {
data_1.virtuals[name][key] = {};
}
data_1.virtuals[name][key] = Object.assign({}, data_1.virtuals[name][key], { get: isGetterSetter.get });
}
if (isGetterSetter.set) {
if (!data_1.virtuals[name]) {
data_1.virtuals[name] = {};
}
if (!data_1.virtuals[name][key]) {
data_1.virtuals[name][key] = {};
}
data_1.virtuals[name][key] = Object.assign({}, data_1.virtuals[name][key], { set: isGetterSetter.set });
}
return;
}
if (isArray) {
utils_1.initAsArray(name, key);
}
else {
utils_1.initAsObject(name, key);
}
const ref = rawOptions.ref;
if (typeof ref === 'string') {
data_1.schema[name][key] = Object.assign({}, data_1.schema[name][key], { type: mongoose.Schema.Types.ObjectId, ref });
return;
}
else if (ref) {
data_1.schema[name][key] = Object.assign({}, data_1.schema[name][key], { type: mongoose.Schema.Types.ObjectId, ref: ref.name });
return;
}
const itemsRef = rawOptions.itemsRef;
if (itemsRef) {
data_1.schema[name][key][0] = Object.assign({}, data_1.schema[name][key][0], { type: mongoose.Schema.Types.ObjectId, ref: itemsRef.name });
return;
}
const enumOption = rawOptions.enum;
if (enumOption) {
if (!Array.isArray(enumOption)) {
rawOptions.enum = Object.keys(enumOption).map((propKey) => enumOption[propKey]);
}
}
// check for validation inconsistencies
if (isWithStringValidate(rawOptions) && !utils_1.isString(Type)) {
throw new errors_1.NotStringTypeError(key);
}
if (isWithNumberValidate(rawOptions) && !utils_1.isNumber(Type)) {
throw new errors_1.NotNumberTypeError(key);
}
const instance = new Type();
const subSchema = data_1.schema[instance.constructor.name];
if (!subSchema && !utils_1.isPrimitive(Type) && !utils_1.isObject(Type)) {
throw new errors_1.InvalidPropError(Type.name, key);
}
const options = _.omit(rawOptions, ['ref', 'items']);
if (utils_1.isPrimitive(Type)) {
if (isArray) {
data_1.schema[name][key][0] = Object.assign({}, data_1.schema[name][key][0], options, { type: Type });
return;
}
data_1.schema[name][key] = Object.assign({}, data_1.schema[name][key], options, { type: Type });
return;
}
// If the 'Type' is not a 'Primitive Type' and no subschema was found treat the type as 'Object'
// so that mongoose can store it as nested document
if (utils_1.isObject(Type) && !subSchema) {
data_1.schema[name][key] = Object.assign({}, data_1.schema[name][key], options, { type: Object });
return;
}
if (isArray) {
data_1.schema[name][key][0] = Object.assign({}, data_1.schema[name][key][0], options, subSchema);
return;
}
const Schema = mongoose.Schema;
const supressSubschemaId = rawOptions._id === false;
data_1.schema[name][key] = Object.assign({}, data_1.schema[name][key], options, { type: new Schema(Object.assign({}, subSchema), supressSubschemaId ? { _id: false } : {}) });
return;
};
exports.prop = (options = {}) => (target, key) => {
const Type = Reflect.getMetadata('design:type', target, key);
if (!Type) {
throw new errors_1.NoMetadataError(key);
}
baseProp(options, Type, target, key);
};
exports.arrayProp = (options) => (target, key) => {
const Type = options.items;
baseProp(options, Type, target, key, true);
};
//# sourceMappingURL=prop.js.map
import 'reflect-metadata';
import * as mongoose from 'mongoose';
export * from './method';
export * from './prop';
export * from './hooks';
export * from './plugin';
export * from '.';
export { getClassForDocument } from './utils';
export declare type InstanceType<T> = T & mongoose.Document;
export declare type ModelType<T> = mongoose.Model<InstanceType<T>> & T;
export interface GetModelForClassOptions {
existingMongoose?: mongoose.Mongoose;
schemaOptions?: mongoose.SchemaOptions;
existingConnection?: mongoose.Connection;
}
export declare class Typegoose {
getModelForClass<T>(t: T, { existingMongoose, schemaOptions, existingConnection }?: GetModelForClassOptions): mongoose.Model<InstanceType<this>> & this & T;
setModelForClass<T>(t: T, { existingMongoose, schemaOptions, existingConnection }?: GetModelForClassOptions): mongoose.Model<InstanceType<this>> & this & T;
private buildSchema;
}
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const mongoose = require("mongoose");
const _ = require("lodash");
mongoose.Promise = global.Promise;
const data_1 = require("./data");
__export(require("./method"));
__export(require("./prop"));
__export(require("./hooks"));
__export(require("./plugin"));
__export(require("."));
var utils_1 = require("./utils");
exports.getClassForDocument = utils_1.getClassForDocument;
class Typegoose {
getModelForClass(t, { existingMongoose, schemaOptions, existingConnection } = {}) {
const name = this.constructor.name;
if (!data_1.models[name]) {
this.setModelForClass(t, { existingMongoose, schemaOptions, existingConnection });
}
return data_1.models[name];
}
setModelForClass(t, { existingMongoose, schemaOptions, existingConnection } = {}) {
const name = this.constructor.name;
// get schema of current model
let sch = this.buildSchema(t, name, schemaOptions);
// get parents class name
let parentCtor = Object.getPrototypeOf(this.constructor.prototype).constructor;
// iterate trough all parents
while (parentCtor && parentCtor.name !== 'Typegoose' && parentCtor.name !== 'Object') {
// extend schema
sch = this.buildSchema(t, parentCtor.name, schemaOptions, sch);
// next parent
parentCtor = Object.getPrototypeOf(parentCtor.prototype).constructor;
}
let model = mongoose.model.bind(mongoose);
if (existingConnection) {
model = existingConnection.model.bind(existingConnection);
}
else if (existingMongoose) {
model = existingMongoose.model.bind(existingMongoose);
}
data_1.models[name] = model(name, sch);
data_1.constructors[name] = this.constructor;
return data_1.models[name];
}
buildSchema(t, name, schemaOptions, sch) {
const Schema = mongoose.Schema;
if (!sch) {
sch = schemaOptions ?
new Schema(data_1.schema[name], schemaOptions) :
new Schema(data_1.schema[name]);
}
else {
sch.add(data_1.schema[name]);
}
const staticMethods = data_1.methods.staticMethods[name];
if (staticMethods) {
sch.statics = Object.assign(staticMethods, sch.statics || {});
}
else {
sch.statics = sch.statics || {};
}
const instanceMethods = data_1.methods.instanceMethods[name];
if (instanceMethods) {
sch.methods = Object.assign(instanceMethods, sch.methods || {});
}
else {
sch.methods = sch.methods || {};
}
if (data_1.hooks[name]) {
const preHooks = data_1.hooks[name].pre;
preHooks.forEach((preHookArgs) => {
sch.pre(...preHookArgs);
});
const postHooks = data_1.hooks[name].post;
postHooks.forEach((postHookArgs) => {
sch.post(...postHookArgs);
});
}
if (data_1.plugins[name]) {
_.forEach(data_1.plugins[name], (plugin) => {
sch.plugin(plugin.mongoosePlugin, plugin.options);
});
}
const getterSetters = data_1.virtuals[name];
_.forEach(getterSetters, (value, key) => {
if (value.get) {
sch.virtual(key).get(value.get);
}
if (value.set) {
sch.virtual(key).set(value.set);
}
});
const indices = Reflect.getMetadata('typegoose:indices', t) || [];
for (const index of indices) {
sch.index(index.fields, index.options);
}
return sch;
}
}
exports.Typegoose = Typegoose;
//# sourceMappingURL=typegoose.js.map
import * as mongoose from 'mongoose';
export declare const isPrimitive: (Type: any) => boolean;
export declare const isObject: (Type: any) => boolean;
export declare const isNumber: (Type: any) => boolean;
export declare const isString: (Type: any) => boolean;
export declare const initAsObject: (name: any, key: any) => void;
export declare const initAsArray: (name: any, key: any) => void;
export declare const getClassForDocument: (document: mongoose.Document) => any;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const data_1 = require("./data");
exports.isPrimitive = (Type) => _.includes(['String', 'Number', 'Boolean', 'Date', 'Decimal128'], Type.name);
exports.isObject = (Type) => {
let prototype = Type.prototype;
let name = Type.name;
while (name) {
if (name === 'Object') {
return true;
}
prototype = Object.getPrototypeOf(prototype);
name = prototype ? prototype.constructor.name : null;
}
return false;
};
exports.isNumber = (Type) => Type.name === 'Number';
exports.isString = (Type) => Type.name === 'String';
exports.initAsObject = (name, key) => {
if (!data_1.schema[name]) {
data_1.schema[name] = {};
}
if (!data_1.schema[name][key]) {
data_1.schema[name][key] = {};
}
};
exports.initAsArray = (name, key) => {
if (!data_1.schema[name]) {
data_1.schema[name] = {};
}
if (!data_1.schema[name][key]) {
data_1.schema[name][key] = [{}];
}
};
exports.getClassForDocument = (document) => {
const modelName = document.constructor.modelName;
return data_1.constructors[modelName];
};
//# sourceMappingURL=utils.js.map
+1
-1
{
"name": "@yued/typegoose",
"version": "5.4.1",
"version": "5.4.2",
"description": "Define Mongoose models using TypeScript classes.",

@@ -5,0 +5,0 @@ "main": "lib/typegoose.js",