@cyberskill/shared 1.217.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +331 -223
- package/dist/config/config.util.d.ts +17 -0
- package/dist/config/env/env.util.d.ts +26 -0
- package/dist/config/eslint/index.d.ts +4 -0
- package/dist/config/graphql-codegen/graphql-codegen.util.d.ts +23 -0
- package/dist/config/vitest/vitest.e2e.cjs +1 -1
- package/dist/config/vitest/vitest.e2e.d.ts +16 -0
- package/dist/config/vitest/vitest.e2e.js +1 -1
- package/dist/config/vitest/vitest.unit.cjs +1 -1
- package/dist/config/vitest/vitest.unit.d.ts +18 -0
- package/dist/config/vitest/vitest.unit.js +1 -1
- package/dist/constant/common.d.ts +4 -0
- package/dist/constant/index.d.ts +3 -0
- package/dist/node/apollo-server/apollo-server.util.d.ts +14 -0
- package/dist/node/command/command.type.d.ts +26 -6
- package/dist/node/command/command.util.d.ts +50 -0
- package/dist/node/express/express.util.d.ts +47 -0
- package/dist/node/fs/fs.type.d.ts +6 -0
- package/dist/node/fs/fs.util.d.ts +48 -1
- package/dist/node/log/log.type.d.ts +6 -1
- package/dist/node/log/log.util.cjs +1 -1
- package/dist/node/log/log.util.d.ts +30 -2
- package/dist/node/log/log.util.js +33 -20
- package/dist/node/mongo/index.cjs +1 -1
- package/dist/node/mongo/index.js +11 -15
- package/dist/node/mongo/mongo.constant.d.ts +5 -0
- package/dist/node/mongo/mongo.type.d.ts +30 -10
- package/dist/node/mongo/mongo.util.cjs +5 -5
- package/dist/node/mongo/mongo.util.d.ts +355 -12
- package/dist/node/mongo/mongo.util.js +686 -190
- package/dist/node/package/package.type.d.ts +2 -2
- package/dist/node/package/package.util.cjs +1 -1
- package/dist/node/package/package.util.d.ts +52 -1
- package/dist/node/package/package.util.js +97 -92
- package/dist/node/path/path.constant.d.ts +9 -0
- package/dist/node/path/path.util.d.ts +24 -0
- package/dist/node/storage/storage.util.d.ts +44 -0
- package/dist/node/storage/storage.util.js +39 -0
- package/dist/node/upload/upload.util.d.ts +21 -0
- package/dist/node/ws/ts.util.d.ts +16 -0
- package/dist/react/apollo-client/apollo-client.component.d.ts +19 -1
- package/dist/react/apollo-client/apollo-client.component.js +1 -4
- package/dist/react/apollo-client/apollo-client.constant.d.ts +5 -0
- package/dist/react/apollo-client/apollo-client.context.d.ts +15 -0
- package/dist/react/apollo-client/apollo-client.hook.d.ts +12 -0
- package/dist/react/apollo-client/apollo-client.util.d.ts +48 -0
- package/dist/react/apollo-client/apollo-client.util.js +9 -0
- package/dist/react/apollo-client-nextjs/apollo-client-nextjs.component.d.ts +19 -1
- package/dist/react/apollo-client-nextjs/apollo-client-nextjs.component.js +1 -4
- package/dist/react/apollo-client-nextjs/apollo-client-nextjs.rsc.d.ts +10 -0
- package/dist/react/apollo-client-nextjs/apollo-client-nextjs.util.d.ts +10 -0
- package/dist/react/apollo-error/apollo-error.component.cjs +1 -1
- package/dist/react/apollo-error/apollo-error.component.d.ts +17 -0
- package/dist/react/apollo-error/apollo-error.component.js +10 -10
- package/dist/react/apollo-error/apollo-error.hook.d.ts +12 -0
- package/dist/react/apollo-error/apollo-error.provider.d.ts +15 -0
- package/dist/react/apollo-error/apollo-error.util.d.ts +17 -0
- package/dist/react/i18next/i18next.hook.d.ts +9 -0
- package/dist/react/i18next/i18next.util.d.ts +10 -0
- package/dist/react/loading/loading.component.d.ts +21 -0
- package/dist/react/loading/loading.hook.d.ts +12 -0
- package/dist/react/loading/loading.provider.d.ts +15 -0
- package/dist/react/log/log.util.d.ts +17 -0
- package/dist/react/next-intl/next-intl.constant.d.ts +9 -0
- package/dist/react/next-intl/next-intl.hoc.d.ts +16 -0
- package/dist/react/next-intl/next-intl.hook.d.ts +21 -0
- package/dist/react/next-intl/next-intl.provider.d.ts +21 -0
- package/dist/react/storage/storage.hook.d.ts +19 -0
- package/dist/react/storage/storage.hook.js +28 -30
- package/dist/react/storage/storage.util.d.ts +39 -0
- package/dist/react/storage/storage.util.js +33 -0
- package/dist/react/userback/userback.component.d.ts +18 -0
- package/dist/typescript/common.type.d.ts +6 -0
- package/dist/typescript/index.d.ts +3 -0
- package/dist/util/common/common.util.d.ts +19 -7
- package/dist/util/common/index.d.ts +3 -0
- package/dist/util/index.d.ts +3 -0
- package/dist/util/object/object.util.d.ts +25 -12
- package/dist/util/serializer/serializer.type.d.ts +1 -1
- package/dist/util/serializer/serializer.util.d.ts +8 -0
- package/dist/util/serializer/serializer.util.js +4 -4
- package/dist/util/string/string.util.cjs +1 -1
- package/dist/util/string/string.util.d.ts +30 -17
- package/dist/util/string/string.util.js +14 -16
- package/dist/util/validate/validate.util.d.ts +9 -3
- package/dist/util/validate/validate.util.js +5 -3
- package/package.json +12 -10
- /package/dist/node_modules/.pnpm/{vitest@3.2.4_@types_debug@4.1.12_@types_node@24.0.14_@vitest_browser@3.2.4_jiti@2.4.2_j_5b4f3b6d03b5e1745ce439b75ce4a42f → vitest@3.2.4_@types_debug@4.1.12_@types_node@24.1.0_@vitest_browser@3.2.4_jiti@2.5.0_js_54cc41e7146dfcdf3e05180c4f422c31}/node_modules/vitest/dist/config.cjs +0 -0
- /package/dist/node_modules/.pnpm/{vitest@3.2.4_@types_debug@4.1.12_@types_node@24.0.14_@vitest_browser@3.2.4_jiti@2.4.2_j_5b4f3b6d03b5e1745ce439b75ce4a42f → vitest@3.2.4_@types_debug@4.1.12_@types_node@24.1.0_@vitest_browser@3.2.4_jiti@2.5.0_js_54cc41e7146dfcdf3e05180c4f422c31}/node_modules/vitest/dist/config.js +0 -0
|
@@ -1 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Environment variable key for MongoDB migration options.
|
|
3
|
+
* This constant defines the environment variable name that can be used to configure
|
|
4
|
+
* MongoDB migration settings and options for database schema management.
|
|
5
|
+
*/
|
|
1
6
|
export declare const MONGO_MIGRATE_OPTIONS = "MONGO_MIGRATE_OPTIONS";
|
|
@@ -48,23 +48,43 @@ export type T_Omit_Update = 'id' | 'createdAt' | 'updatedAt';
|
|
|
48
48
|
interface I_VirtualNestedOptions {
|
|
49
49
|
[key: string]: I_VirtualNestedOptions | number | string | boolean;
|
|
50
50
|
}
|
|
51
|
-
|
|
52
|
-
|
|
51
|
+
/**
|
|
52
|
+
* Function type for dynamically determining the reference model name.
|
|
53
|
+
* Can return either a string (model name) or an enum value that represents the model.
|
|
54
|
+
* The function can also return undefined, which will be handled gracefully.
|
|
55
|
+
* This allows for optional properties in documents without requiring non-null assertions.
|
|
56
|
+
*
|
|
57
|
+
* @template T - The document type
|
|
58
|
+
* @template R - The return type (string or enum)
|
|
59
|
+
*/
|
|
60
|
+
type T_DynamicRefFunction<T = unknown, R extends string = string> = (doc: T) => R | undefined;
|
|
61
|
+
interface I_VirtualBaseOptions {
|
|
53
62
|
localField: string;
|
|
54
63
|
foreignField: string;
|
|
55
64
|
count?: boolean;
|
|
56
65
|
justOne?: boolean;
|
|
57
66
|
options?: I_VirtualNestedOptions;
|
|
58
67
|
}
|
|
59
|
-
interface
|
|
68
|
+
interface I_VirtualOptions extends I_VirtualBaseOptions {
|
|
69
|
+
ref: string;
|
|
70
|
+
}
|
|
71
|
+
export interface I_DynamicVirtualOptions<T, R extends string = string> extends I_VirtualBaseOptions {
|
|
72
|
+
ref: T_DynamicRefFunction<T, R>;
|
|
73
|
+
}
|
|
74
|
+
export type T_VirtualOptions<T, R extends string = string> = I_VirtualOptions | I_DynamicVirtualOptions<T, R>;
|
|
75
|
+
export interface I_DynamicVirtualConfig<T, R extends string = string> {
|
|
76
|
+
name: string;
|
|
77
|
+
options: I_DynamicVirtualOptions<T, R>;
|
|
78
|
+
}
|
|
79
|
+
interface I_MongooseOptions<T, R extends string = string> {
|
|
60
80
|
mongoose: typeof mongoose;
|
|
61
81
|
virtuals?: {
|
|
62
82
|
name: keyof T | string;
|
|
63
|
-
options?:
|
|
83
|
+
options?: T_VirtualOptions<T, R>;
|
|
64
84
|
get?: (this: T) => void;
|
|
65
85
|
}[];
|
|
66
86
|
}
|
|
67
|
-
export interface I_CreateSchemaOptions<T> extends I_MongooseOptions<T> {
|
|
87
|
+
export interface I_CreateSchemaOptions<T, R extends string = string> extends I_MongooseOptions<T, R> {
|
|
68
88
|
schema: T_Input_MongooseSchema<T>;
|
|
69
89
|
standalone?: boolean;
|
|
70
90
|
}
|
|
@@ -77,7 +97,7 @@ export interface I_MongooseModelMiddleware<T extends Partial<C_Document>> {
|
|
|
77
97
|
pre?: T_MongooseMiddlewarePreFunction<T & T_QueryWithHelpers<T>>;
|
|
78
98
|
post?: T_MongooseMiddlewarePostFunction<T>;
|
|
79
99
|
}
|
|
80
|
-
export interface I_CreateModelOptions<T extends Partial<C_Document
|
|
100
|
+
export interface I_CreateModelOptions<T extends Partial<C_Document>, R extends string = string> extends I_MongooseOptions<T, R> {
|
|
81
101
|
schema: T_Input_MongooseSchema<T>;
|
|
82
102
|
name: string;
|
|
83
103
|
aggregate?: boolean;
|
|
@@ -85,7 +105,7 @@ export interface I_CreateModelOptions<T extends Partial<C_Document>> extends I_M
|
|
|
85
105
|
pagination?: boolean;
|
|
86
106
|
}
|
|
87
107
|
export type T_Input_Populate = string | string[] | T_PopulateOptions | T_PopulateOptions[];
|
|
88
|
-
export interface
|
|
108
|
+
export interface I_PaginateOptionsWithPopulate extends T_PaginateOptions, Omit<T_PopulateOption, 'populate'> {
|
|
89
109
|
populate?: T_Input_Populate;
|
|
90
110
|
}
|
|
91
111
|
export interface I_Input_FindOne<T> extends T_PopulateOption {
|
|
@@ -99,14 +119,14 @@ export interface I_Input_FindAll<T> extends T_PopulateOption {
|
|
|
99
119
|
options?: T_QueryOptions<T>;
|
|
100
120
|
}
|
|
101
121
|
export type I_Input_FindPaging<T = undefined> = T extends undefined ? {
|
|
102
|
-
options?:
|
|
122
|
+
options?: I_PaginateOptionsWithPopulate;
|
|
103
123
|
} : {
|
|
104
124
|
filter?: T_FilterQuery<T>;
|
|
105
|
-
options?:
|
|
125
|
+
options?: I_PaginateOptionsWithPopulate;
|
|
106
126
|
};
|
|
107
127
|
export interface I_Input_FindPagingAggregate {
|
|
108
128
|
pipeline: T_PipelineStage[];
|
|
109
|
-
options?:
|
|
129
|
+
options?: I_PaginateOptionsWithPopulate;
|
|
110
130
|
}
|
|
111
131
|
export interface I_Input_CreateOne<T> {
|
|
112
132
|
doc: T;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
module.exports = ${JSON.stringify(n,null,4)}`;
|
|
3
|
-
${
|
|
4
|
-
`;
|
|
5
|
-
`).includes(f.MIGRATE_MONGO_CONFIG)||y.appendFileSync(f.PATH.GIT_IGNORE,e):y.writeFileSync(f.PATH.GIT_IGNORE,e)}}),regexify(n,t){if(!n)return{};let e=p.cloneDeep(n);if(!t||t.length===0)return e;for(const r of t){const s=r.toString().split("."),u=D.getNestedValue(e,s);if(typeof u=="string"&&u.length>0){const c={$regex:`.*${x.regexSearchMapper(u)}.*`,$options:"i"};e=D.setNestedValue(e,s,c)}}return e}};class U{constructor(t,e){G(this,"collection"),this.collection=t.collection(e)}createOne(t){return o(this,null,function*(){try{const e=h(h({},g.createGenericFields()),t);return(yield this.collection.insertOne(e)).acknowledged?{success:!0,message:"Document created successfully",result:e}:{success:!1,message:"Document creation failed",code:d.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(e){return i.catchError(e)}})}createMany(t){return o(this,null,function*(){try{const e=t.map(s=>h(h({},g.createGenericFields()),s)),r=yield this.collection.insertMany(e);return r.insertedCount===0?{success:!1,message:"No documents were inserted",code:d.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:`${r.insertedCount} documents created successfully`,result:e}}catch(e){return i.catchError(e)}})}findOne(t){return o(this,null,function*(){try{const e=yield this.collection.findOne(t);return e?{success:!0,message:"Document found",result:e}:{success:!1,message:"Document not found",code:d.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(e){return i.catchError(e)}})}findAll(){return o(this,arguments,function*(t={}){try{return{success:!0,message:"Documents retrieved successfully",result:yield this.collection.find(t).toArray()}}catch(e){return i.catchError(e)}})}count(){return o(this,arguments,function*(t={}){try{return{success:!0,message:"Count retrieved successfully",result:yield this.collection.countDocuments(t)}}catch(e){return i.catchError(e)}})}updateOne(t,e){return o(this,null,function*(){try{const r=yield this.collection.updateOne(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:d.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document updated successfully",result:r}}catch(r){return i.catchError(r)}})}updateMany(t,e){return o(this,null,function*(){try{const r=yield this.collection.updateMany(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:d.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents updated successfully",result:r}}catch(r){return i.catchError(r)}})}deleteOne(t){return o(this,null,function*(){try{const e=yield this.collection.deleteOne(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:d.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document deleted successfully",result:e}}catch(e){return i.catchError(e)}})}deleteMany(t){return o(this,null,function*(){try{const e=yield this.collection.deleteMany(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:d.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents deleted successfully",result:e}}catch(e){return i.catchError(e)}})}}class ${constructor(t){this.model=t}getModelName(){return this.model.modelName}findOne(){return o(this,arguments,function*(t={},e={},r={},s){try{const u=this.model.findOne(t,e,r);s&&u.populate(s);const c=yield u.exec();return c?{success:!0,result:c}:{success:!1,message:`No ${this.getModelName()} found.`,code:d.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(u){return i.catchError(u)}})}findAll(){return o(this,arguments,function*(t={},e={},r={},s){try{const u=this.model.find(t,e,r);return s&&u.populate(s),{success:!0,result:yield u.exec()}}catch(u){return i.catchError(u)}})}findPaging(){return o(this,arguments,function*(t={},e={}){try{return{success:!0,result:yield this.model.paginate(t,e)}}catch(r){return i.catchError(r)}})}findPagingAggregate(t){return o(this,arguments,function*(e,r={}){try{return{success:!0,result:yield this.model.aggregatePaginate(this.model.aggregate(e),r)}}catch(s){return i.catchError(s)}})}count(){return o(this,arguments,function*(t={}){try{return{success:!0,result:yield this.model.countDocuments(t)}}catch(e){return i.catchError(e)}})}createOne(t){return o(this,null,function*(){try{return{success:!0,result:yield this.model.create(t)}}catch(e){return i.catchError(e)}})}createMany(t){return o(this,arguments,function*(e,r={}){try{return{success:!0,result:(yield this.model.insertMany(e,r)).map(c=>c instanceof q.Document?c.toObject():null).filter(c=>c!==null)}}catch(s){return i.catchError(s)}})}updateOne(){return o(this,arguments,function*(t={},e={},r={}){try{const s=yield this.model.findOneAndUpdate(t,e,h({new:!0},r)).exec();return s?{success:!0,result:s}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:d.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(s){return i.catchError(s)}})}updateMany(){return o(this,arguments,function*(t={},e={},r={}){try{return{success:!0,result:yield this.model.updateMany(t,e,r).exec()}}catch(s){return i.catchError(s)}})}deleteOne(){return o(this,arguments,function*(t={},e={}){try{const r=yield this.model.findOneAndDelete(t,e).exec();return r?{success:!0,result:r}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:d.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return i.catchError(r)}})}deleteMany(){return o(this,arguments,function*(t={},e={}){try{const r=yield this.model.deleteMany(t,e).exec();return r.deletedCount===0?{success:!1,message:"No documents found to delete.",code:d.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:r}}catch(r){return i.catchError(r)}})}createShortId(t,e=4){return o(this,null,function*(){try{const s=new Set;for(let u=0;u<10;u++){const c=S.generateShortId(t,u+e);if(!s.has(c)&&(s.add(c),!(yield this.model.exists({shortId:c}))))return{success:!0,result:c}}return{success:!1,message:"Failed to create a unique shortId",code:d.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return i.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,filter:s}){const u=h({},s!=null?s:{});return r?R(h({},u),{$or:[{[`slug.${e}`]:t},{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]}):R(h({},u),{$or:[{slug:t},{slugHistory:t}]})}createUniqueSlug(t){return o(this,arguments,function*({slug:e,field:r,isObject:s,filter:u}){const c=S.generateSlug(e);let l=c,a=1;for(;yield this.model.exists(this.createSlugQuery({slug:l,field:r,isObject:s,filter:u}));)l=`${c}-${a++}`;return l})}createSlug(t){return o(this,arguments,function*({field:e,from:r,filter:s}){try{const u=r[e];return p.isObject(u)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(u).map(m=>o(this,[m],function*([E,O]){const N=yield this.createUniqueSlug({slug:O,field:E,isObject:!0,filter:s});return[E,N]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:u,field:e,isObject:!1,filter:s})}}catch(u){return i.catchError(u)}})}checkSlug(t){return o(this,arguments,function*({slug:e,field:r,from:s,filter:u}){try{const c=s[r];if(p.isObject(c)){for(const E of Object.values(c)){const O=S.generateSlug(E);if(yield this.model.exists(this.createSlugQuery({slug:O,field:r,isObject:!0,filter:u})))return{success:!0,result:!0}}return{success:!0,result:!1}}const a=S.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:a,field:r,isObject:!1,filter:u})))!==null}}catch(c){return i.catchError(c)}})}aggregate(t){return o(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return i.catchError(e)}})}}exports.aggregatePaginate=A;exports.mongoosePaginate=b;exports.MongoController=U;exports.MongooseController=$;exports.mongo=g;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("lodash-es"),B=require("migrate-mongo"),k=require("mongoose"),H=require("mongoose-aggregate-paginate-v2"),K=require("mongoose-paginate-v2"),U=require("uuid"),$=require("../../util/object/object.util.cjs"),W=require("../../util/common/common.util.cjs"),P=require("../fs/fs.util.cjs"),A=require("../path/path.constant.cjs"),Q=require("../../util/validate/validate.util.cjs"),I=require("../../util/string/string.util.cjs"),v=require("../../constant/response-status.cjs"),f=require("../log/log.util.cjs");var z=Object.defineProperty,J=Object.defineProperties,X=Object.getOwnPropertyDescriptors,G=Object.getOwnPropertySymbols,Y=Object.prototype.hasOwnProperty,Z=Object.prototype.propertyIsEnumerable,F=(n,t,e)=>t in n?z(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,O=(n,t)=>{for(var e in t||(t={}))Y.call(t,e)&&F(n,e,t[e]);if(G)for(var e of G(t))Z.call(t,e)&&F(n,e,t[e]);return n},V=(n,t)=>J(n,X(t)),ee=(n,t,e)=>F(n,typeof t!="symbol"?t+"":t,e),a=(n,t,e)=>new Promise((r,s)=>{var c=i=>{try{o(e.next(i))}catch(l){s(l)}},u=i=>{try{o(e.throw(i))}catch(l){s(l)}},o=i=>i.done?r(i.value):Promise.resolve(i.value).then(c,u);o((e=e.apply(n,t)).next())});function te(n){return n===n.toUpperCase()?n.charAt(0).toUpperCase()+n.slice(1).toLowerCase():n}const T={createGenericFields(){return{id:U.v4(),isDel:!1,createdAt:new Date,updatedAt:new Date}},applyPlugins(n,t){t.filter(e=>typeof e=="function").forEach(e=>n.plugin(e))},applyMiddlewares(n,t){t.forEach(({method:e,pre:r,post:s})=>{e&&r&&n.pre(e,r),e&&s&&n.post(e,s)})},createGenericSchema(n){return new n.Schema({id:{type:String,default:U.v4,unique:!0},isDel:{type:Boolean,default:!1}},{timestamps:!0})},createSchema({mongoose:n,schema:t,virtuals:e=[],standalone:r=!1}){const s=new n.Schema(t);return e.forEach(({name:c,options:u,get:o})=>{if(T.isDynamicVirtual(u)){const i=s.statics;i._dynamicVirtuals||(i._dynamicVirtuals=[]),i._dynamicVirtuals.push({name:c,options:u});const l=s.virtual(c);o?l.get(o):l.get(function(){var d;return((d=this._populated)==null?void 0:d[c])||(u!=null&&u.count?0:u!=null&&u.justOne?null:[])})}else{const i=s.virtual(c,u);o&&i.get(o)}}),r||s.add(T.createGenericSchema(n)),s},createModel({mongoose:n,name:t,schema:e,pagination:r=!1,aggregate:s=!1,virtuals:c=[],middlewares:u=[]}){if(!t)throw new Error("Model name is required.");if(n.models[t])return n.models[t];const o=T.createSchema({mongoose:n,schema:e,virtuals:c});return T.applyPlugins(o,[r&&K,s&&H]),T.applyMiddlewares(o,u),n.model(t,o)},validator:{isRequired(){return function(n){return a(this,null,function*(){return!Q.validate.isEmpty(n)})}},isUnique(n){return function(t){return a(this,null,function*(){if(!Array.isArray(n)||n.length===0)throw new Error("Fields must be a non-empty array of strings.");const e={$or:n.map(s=>({[s]:t}))};return!(yield this.constructor.exists(e))})}},matchesRegex(n){return function(t){return a(this,null,function*(){if(!Array.isArray(n)||n.some(e=>!(e instanceof RegExp)))throw new Error("regexArray must be an array of valid RegExp objects.");return n.every(e=>e.test(t))})}}},migrate:V(O({},B),{setConfig:n=>{const t=`// This file is automatically generated by the Cyberskill CLI.
|
|
2
|
+
module.exports = ${JSON.stringify(n,null,4)}`;P.writeFileSync(A.PATH.MIGRATE_MONGO_CONFIG,t);const e=`
|
|
3
|
+
${A.MIGRATE_MONGO_CONFIG}
|
|
4
|
+
`;P.pathExistsSync(A.PATH.GIT_IGNORE)?P.readFileSync(A.PATH.GIT_IGNORE,"utf-8").split(`
|
|
5
|
+
`).includes(A.MIGRATE_MONGO_CONFIG)||P.appendFileSync(A.PATH.GIT_IGNORE,e):P.writeFileSync(A.PATH.GIT_IGNORE,e)}}),regexify(n,t){if(!n)return{};let e=j.cloneDeep(n);if(!t||t.length===0)return e;for(const r of t){const s=r.toString().split("."),c=$.getNestedValue(e,s);if(typeof c=="string"&&c.length>0){const u={$regex:`.*${W.regexSearchMapper(c)}.*`,$options:"i"};e=$.setNestedValue(e,s,u)}}return e},isDynamicVirtual(n){return!!(n&&typeof n.ref=="function")}};function re(n){return n!==null&&typeof n=="object"&&"toObject"in n&&typeof n.toObject=="function"}function se(n,t,e){if(!n.length||!t||!(e!=null&&e.ref))return[];const r=new Map;return n.forEach(s=>{try{const c=e.ref(s);if(c==null)return;const u=typeof c=="string"?c:String(c);if(u&&u.trim()!==""){const o=te(u);r.has(o)||r.set(o,[]),r.get(o).push(s)}}catch(c){f.catchError(new Error(`Dynamic ref function failed for virtual "${t}": ${c instanceof Error?c.message:String(c)}`))}}),Array.from(r.entries()).map(([s,c])=>({model:s,docs:c}))}function q(n,t,e,r,s){return a(this,null,function*(){if(!t.length||!e.length||!r)return t;const c=e.filter(i=>{if(Array.isArray(r))return r.length>0&&r.some(l=>typeof l=="string"?l===i.name:l.path===i.name);if(typeof r=="string")return r===i.name;if(typeof r=="object"&&r!==null){const l=r;return l.path&&l.path===i.name||l.populate&&l.populate===i.name}return!1});if(c.length===0)return t;const u=j.cloneDeep(t.map(i=>re(i)?i.toObject():i));u.forEach(i=>{c.forEach(({name:l,options:d})=>{if(!(l in i)){const h=i;h[l]=d.count?0:d.justOne?null:[]}})});const o=new Map;for(const i of c){const{name:l,options:d}=i,h=se(u,l,d);for(const S of h){o.has(S.model)||o.set(S.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const m=o.get(S.model);m.virtuals.find(D=>D.name===l)||(m.virtuals.push(i),m.localValueSets.set(l,new Set));const M=m.localValueSets.get(l);S.docs.forEach(D=>{const C=D[d.localField];if(C!=null){const _=String(C);M.add(_);let R=-1;const N=D;N.id!==void 0?R=u.findIndex(b=>b.id===N.id):N._id!==void 0&&(R=u.findIndex(b=>{var E,g,p,y;return((g=(E=b._id)==null?void 0:E.toString)==null?void 0:g.call(E))===((y=(p=N._id)==null?void 0:p.toString)==null?void 0:y.call(p))})),R!==-1&&(m.docsByLocalValue.has(_)||m.docsByLocalValue.set(_,[]),m.docsByLocalValue.get(_).push(R))}})}}return yield Promise.all(Array.from(o.entries()).map(i=>a(null,[i],function*([l,d]){const h=n.models[l];if(!h)return;const S=new Set;if(d.localValueSets.forEach(_=>{_.forEach(R=>S.add(R))}),S.size===0)return;const m=[...new Set(d.virtuals.map(_=>_.options.foreignField))],M=Array.from(S);let D;m.length===1?D={[String(m[0])]:{$in:M}}:D={$or:m.map(_=>({[_]:{$in:M}}))};const C=yield h.find(D,s).lean();for(const _ of d.virtuals){const{name:R,options:N}=_,b=C.filter(E=>{const g=E[N.foreignField];return g!=null&&S.has(String(g))});if(N.count){const E=new Map;b.forEach(g=>{var p;const y=(p=g[N.foreignField])==null?void 0:p.toString();y&&E.set(y,(E.get(y)||0)+1)}),d.localValueSets.get(R).forEach(g=>{const p=d.docsByLocalValue.get(g)||[],y=E.get(g)||0;p.forEach(w=>{const x=u[w];x[R]===void 0&&(x[R]=y)})})}else{const E=new Map;b.forEach(g=>{var p;const y=(p=g[N.foreignField])==null?void 0:p.toString();y&&(E.has(y)||E.set(y,[]),E.get(y).push(g))}),d.localValueSets.get(R).forEach(g=>{const p=d.docsByLocalValue.get(g)||[],y=E.get(g)||[],w=N.justOne?y[0]||null:y;p.forEach(x=>{const L=u[x];L[R]=w})})}}}))),u})}class ne{constructor(t,e){ee(this,"collection"),this.collection=t.collection(e)}createOne(t){return a(this,null,function*(){try{const e=O(O({},T.createGenericFields()),t);return(yield this.collection.insertOne(e)).acknowledged?{success:!0,message:"Document created successfully",result:e}:{success:!1,message:"Document creation failed",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(e){return f.catchError(e)}})}createMany(t){return a(this,null,function*(){try{const e=t.map(s=>O(O({},T.createGenericFields()),s)),r=yield this.collection.insertMany(e);return r.insertedCount===0?{success:!1,message:"No documents were inserted",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:`${r.insertedCount} documents created successfully`,result:e}}catch(e){return f.catchError(e)}})}findOne(t){return a(this,null,function*(){try{const e=yield this.collection.findOne(t);return e?{success:!0,message:"Document found",result:e}:{success:!1,message:"Document not found",code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(e){return f.catchError(e)}})}findAll(){return a(this,arguments,function*(t={}){try{return{success:!0,message:"Documents retrieved successfully",result:yield this.collection.find(t).toArray()}}catch(e){return f.catchError(e)}})}count(){return a(this,arguments,function*(t={}){try{const e=yield this.collection.countDocuments(t);return{success:!0,message:`${e} documents counted successfully`,result:e}}catch(e){return f.catchError(e)}})}updateOne(t,e){return a(this,null,function*(){try{const r=yield this.collection.updateOne(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document updated successfully",result:r}}catch(r){return f.catchError(r)}})}updateMany(t,e){return a(this,null,function*(){try{const r=yield this.collection.updateMany(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents updated successfully",result:r}}catch(r){return f.catchError(r)}})}deleteOne(t){return a(this,null,function*(){try{const e=yield this.collection.deleteOne(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document deleted successfully",result:e}}catch(e){return f.catchError(e)}})}deleteMany(t){return a(this,null,function*(){try{const e=yield this.collection.deleteMany(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents deleted successfully",result:e}}catch(e){return f.catchError(e)}})}}class ce{constructor(t){this.model=t}getModelName(){return this.model.modelName}findOne(){return a(this,arguments,function*(t={},e={},r={},s){try{const c=this.model.findOne(t,e,r),o=this.model.schema.statics._dynamicVirtuals;s&&(!o||o.length===0)&&c.populate(s);const i=yield c.exec();if(!i)return{success:!1,message:`No ${this.getModelName()} found.`,code:v.RESPONSE_STATUS.NOT_FOUND.CODE};let l=i;if(o&&o.length>0){const d=yield q(this.model.base,[i],o,s);l=d&&d[0]?d[0]:i}return{success:!0,result:l}}catch(c){return f.catchError(c)}})}findAll(){return a(this,arguments,function*(t={},e={},r={},s){try{const c=this.model.find(t,e,r),o=this.model.schema.statics._dynamicVirtuals;s&&(!o||o.length===0)&&c.populate(s);const i=yield c.exec();let l=i;return o&&o.length>0&&i.length>0&&(l=yield q(this.model.base,i,o,s)),{success:!0,result:l}}catch(c){return f.catchError(c)}})}findPaging(){return a(this,arguments,function*(t={},e={}){try{const s=this.model.schema.statics._dynamicVirtuals,c=O({},e);s&&s.length>0&&(c.populate=void 0);const u=yield this.model.paginate(t,c);let o=u.docs;return s&&s.length>0&&u.docs.length>0&&(o=yield q(this.model.base,u.docs,s,e.populate)),{success:!0,result:V(O({},u),{docs:o})}}catch(r){return f.catchError(r)}})}findPagingAggregate(t){return a(this,arguments,function*(e,r={}){try{const c=this.model.schema.statics._dynamicVirtuals,u=O({},r);c&&c.length>0&&(u.populate=void 0);const o=yield this.model.aggregatePaginate(this.model.aggregate(e),u);let i=o.docs;return c&&c.length>0&&o.docs.length>0&&(i=yield q(this.model.base,o.docs,c,r.populate)),{success:!0,result:V(O({},o),{docs:i})}}catch(s){return f.catchError(s)}})}count(){return a(this,arguments,function*(t={}){try{return{success:!0,result:yield this.model.countDocuments(t)}}catch(e){return f.catchError(e)}})}createOne(t){return a(this,null,function*(){try{return{success:!0,result:yield this.model.create(t)}}catch(e){return f.catchError(e)}})}createMany(t){return a(this,arguments,function*(e,r={}){try{return{success:!0,result:(yield this.model.insertMany(e,r)).map(u=>u instanceof k.Document?u.toObject():null).filter(u=>u!==null)}}catch(s){return f.catchError(s)}})}updateOne(){return a(this,arguments,function*(t={},e={},r={}){try{const s=yield this.model.findOneAndUpdate(t,e,O({new:!0},r)).exec();return s?{success:!0,result:s}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(s){return f.catchError(s)}})}updateMany(){return a(this,arguments,function*(t={},e={},r={}){try{return{success:!0,result:yield this.model.updateMany(t,e,r).exec()}}catch(s){return f.catchError(s)}})}deleteOne(){return a(this,arguments,function*(t={},e={}){try{const r=yield this.model.findOneAndDelete(t,e).exec();return r?{success:!0,result:r}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return f.catchError(r)}})}deleteMany(){return a(this,arguments,function*(t={},e={}){try{const r=yield this.model.deleteMany(t,e).exec();return r.deletedCount===0?{success:!1,message:"No documents found to delete.",code:v.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:r}}catch(r){return f.catchError(r)}})}createShortId(t,e=4){return a(this,null,function*(){try{const s=Array.from({length:10},(o,i)=>I.generateShortId(t,i+e)),u=(yield Promise.all(s.map(o=>this.model.exists({shortId:o})))).findIndex(o=>!o);if(u!==-1){const o=s[u];if(o)return{success:!0,result:o}}return{success:!1,message:"Failed to create a unique shortId",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return f.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,filter:s}){const c=O({},s!=null?s:{});return r?V(O({},c),{$or:[{[`slug.${e}`]:t},{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]}):V(O({},c),{$or:[{slug:t},{slugHistory:t}]})}createUniqueSlug(t){return a(this,arguments,function*({slug:e,field:r,isObject:s,filter:c}){const u=I.generateSlug(e),i=Array.from({length:100},(h,S)=>S===0?u:`${u}-${S}`),d=(yield Promise.all(i.map(h=>this.model.exists(this.createSlugQuery({slug:h,field:r,isObject:s,filter:c}))))).findIndex(h=>!h);if(d!==-1){const h=i[d];if(h)return h}return`${u}-${Date.now()}`})}createSlug(t){return a(this,arguments,function*({field:e,from:r,filter:s}){try{const c=r[e];return j.isObject(c)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(c).map(l=>a(this,[l],function*([d,h]){const S=yield this.createUniqueSlug({slug:h,field:d,isObject:!0,filter:s});return[d,S]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:c,field:e,isObject:!1,filter:s})}}catch(c){return f.catchError(c)}})}checkSlug(t){return a(this,arguments,function*({slug:e,field:r,from:s,filter:c}){try{const u=s[r];if(j.isObject(u)){const h=Object.values(u).map(m=>I.generateSlug(m));return(yield Promise.all(h.map(m=>this.model.exists(this.createSlugQuery({slug:m,field:r,isObject:!0,filter:c}))))).some(m=>m)?{success:!0,result:!0}:{success:!0,result:!1}}const i=I.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:i,field:r,isObject:!1,filter:c})))!==null}}catch(u){return f.catchError(u)}})}aggregate(t){return a(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return f.catchError(e)}})}}exports.MongoController=ne;exports.MongooseController=ce;exports.mongo=T;
|
|
@@ -1,14 +1,46 @@
|
|
|
1
1
|
import { default as mongooseRaw } from 'mongoose';
|
|
2
2
|
import { default as migrate } from 'migrate-mongo';
|
|
3
|
-
import { default as aggregatePaginate } from 'mongoose-aggregate-paginate-v2';
|
|
4
|
-
import { default as mongoosePaginate } from 'mongoose-paginate-v2';
|
|
5
3
|
import { I_Return } from '../../typescript/index.js';
|
|
6
|
-
import { C_Db, C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DeleteOptionsExtended, I_ExtendedModel, I_GenericDocument, I_Input_CheckSlug, I_Input_CreateSlug, I_Input_GenerateSlug, I_MongooseModelMiddleware, I_UpdateOptionsExtended, T_AggregatePaginateResult, T_DeleteResult, T_Filter, T_FilterQuery, T_Input_Populate, T_InsertManyOptions, T_MongoosePlugin, T_MongooseShema,
|
|
7
|
-
|
|
4
|
+
import { C_Db, C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DeleteOptionsExtended, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_Input_CheckSlug, I_Input_CreateSlug, I_Input_GenerateSlug, I_MongooseModelMiddleware, I_PaginateOptionsWithPopulate, I_UpdateOptionsExtended, T_AggregatePaginateResult, T_DeleteResult, T_Filter, T_FilterQuery, T_Input_Populate, T_InsertManyOptions, T_MongoosePlugin, T_MongooseShema, T_PaginateResult, T_PipelineStage, T_ProjectionType, T_QueryOptions, T_UpdateQuery, T_UpdateResult, T_VirtualOptions, T_WithId } from './mongo.type.js';
|
|
5
|
+
/**
|
|
6
|
+
* MongoDB utility object providing comprehensive database operations and utilities.
|
|
7
|
+
* This object contains methods for creating generic fields, applying plugins and middlewares,
|
|
8
|
+
* creating schemas and models, validation functions, migration utilities, and regex filtering.
|
|
9
|
+
*/
|
|
8
10
|
export declare const mongo: {
|
|
11
|
+
/**
|
|
12
|
+
* Creates generic fields that are commonly used across MongoDB documents.
|
|
13
|
+
* This function generates standard fields including a UUID, deletion flag, and timestamps
|
|
14
|
+
* that can be applied to any document schema.
|
|
15
|
+
*
|
|
16
|
+
* @returns An object containing generic document fields (id, isDel, createdAt, updatedAt).
|
|
17
|
+
*/
|
|
9
18
|
createGenericFields(): I_GenericDocument;
|
|
19
|
+
/**
|
|
20
|
+
* Applies plugins to a Mongoose schema.
|
|
21
|
+
* This function filters out falsy plugins and applies the remaining valid plugins
|
|
22
|
+
* to the provided schema.
|
|
23
|
+
*
|
|
24
|
+
* @param schema - The Mongoose schema to apply plugins to.
|
|
25
|
+
* @param plugins - An array of plugin functions or false values to filter and apply.
|
|
26
|
+
*/
|
|
10
27
|
applyPlugins<T>(schema: T_MongooseShema<T>, plugins: Array<T_MongoosePlugin | false>): void;
|
|
28
|
+
/**
|
|
29
|
+
* Applies middleware functions to a Mongoose schema.
|
|
30
|
+
* This function configures pre and post middleware for specified methods on the schema.
|
|
31
|
+
*
|
|
32
|
+
* @param schema - The Mongoose schema to apply middleware to.
|
|
33
|
+
* @param middlewares - An array of middleware configurations with method, pre, and post functions.
|
|
34
|
+
*/
|
|
11
35
|
applyMiddlewares<T extends Partial<C_Document>>(schema: T_MongooseShema<T>, middlewares: I_MongooseModelMiddleware<T>[]): void;
|
|
36
|
+
/**
|
|
37
|
+
* Creates a generic Mongoose schema with common fields.
|
|
38
|
+
* This function creates a base schema with UUID field and deletion flag,
|
|
39
|
+
* configured with automatic timestamps.
|
|
40
|
+
*
|
|
41
|
+
* @param mongoose - The Mongoose instance to create the schema with.
|
|
42
|
+
* @returns A Mongoose schema with generic document fields.
|
|
43
|
+
*/
|
|
12
44
|
createGenericSchema(mongoose: typeof mongooseRaw): mongooseRaw.Schema<I_GenericDocument, mongooseRaw.Model<I_GenericDocument, any, any, any, mongooseRaw.Document<unknown, any, I_GenericDocument, any> & I_GenericDocument & Required<{
|
|
13
45
|
_id: unknown;
|
|
14
46
|
}> & {
|
|
@@ -18,58 +50,331 @@ export declare const mongo: {
|
|
|
18
50
|
}> & {
|
|
19
51
|
__v: number;
|
|
20
52
|
}>;
|
|
21
|
-
|
|
22
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Creates a Mongoose schema with optional virtual fields and generic fields.
|
|
55
|
+
* This function creates a new Mongoose schema from the provided schema definition,
|
|
56
|
+
* optionally adds virtual fields, and includes generic fields (unless standalone is true).
|
|
57
|
+
*
|
|
58
|
+
* @param options - Configuration options including mongoose instance, schema definition, virtuals, and standalone flag.
|
|
59
|
+
* @param options.mongoose - The Mongoose instance to use for schema creation.
|
|
60
|
+
* @param options.schema - The schema definition object.
|
|
61
|
+
* @param options.virtuals - Optional array of virtual field configurations.
|
|
62
|
+
* @param options.standalone - Whether to exclude generic fields (default: false).
|
|
63
|
+
* @returns A configured Mongoose schema.
|
|
64
|
+
*/
|
|
65
|
+
createSchema<T, R extends string = string>({ mongoose, schema, virtuals, standalone, }: I_CreateSchemaOptions<T, R>): T_MongooseShema<T>;
|
|
66
|
+
/**
|
|
67
|
+
* Creates a Mongoose model with plugins, middleware, and pagination support.
|
|
68
|
+
* This function creates a model from a schema with optional pagination and aggregation plugins,
|
|
69
|
+
* and applies any specified middleware. If a model with the same name already exists, it returns the existing model.
|
|
70
|
+
*
|
|
71
|
+
* @param options - Configuration options including mongoose instance, model name, schema, and feature flags.
|
|
72
|
+
* @param options.mongoose - The Mongoose instance to use for model creation.
|
|
73
|
+
* @param options.name - The name of the model to create.
|
|
74
|
+
* @param options.schema - The schema definition for the model.
|
|
75
|
+
* @param options.pagination - Whether to enable pagination plugin (default: false).
|
|
76
|
+
* @param options.aggregate - Whether to enable aggregation pagination plugin (default: false).
|
|
77
|
+
* @param options.virtuals - Optional array of virtual field configurations.
|
|
78
|
+
* @param options.middlewares - Optional array of middleware configurations.
|
|
79
|
+
* @returns A configured Mongoose model with extended functionality.
|
|
80
|
+
* @throws {Error} When the model name is not provided.
|
|
81
|
+
*/
|
|
82
|
+
createModel<T extends Partial<C_Document>, R extends string = string>({ mongoose: currentMongooseInstance, name, schema, pagination, aggregate, virtuals, middlewares, }: I_CreateModelOptions<T, R>): I_ExtendedModel<T>;
|
|
83
|
+
/**
|
|
84
|
+
* Validation utilities for Mongoose schemas.
|
|
85
|
+
* This object provides common validation functions that can be used in Mongoose schema definitions.
|
|
86
|
+
*/
|
|
23
87
|
validator: {
|
|
88
|
+
/**
|
|
89
|
+
* Creates a required field validator.
|
|
90
|
+
* This function returns a validator that checks if a field value is not empty
|
|
91
|
+
* using the validate.isEmpty utility.
|
|
92
|
+
*
|
|
93
|
+
* @returns A validation function that returns true if the field is not empty.
|
|
94
|
+
*/
|
|
24
95
|
isRequired<T>(): (this: T, value: unknown) => Promise<boolean>;
|
|
96
|
+
/**
|
|
97
|
+
* Creates a unique field validator.
|
|
98
|
+
* This function returns a validator that checks if a field value is unique
|
|
99
|
+
* across the specified fields in the collection.
|
|
100
|
+
*
|
|
101
|
+
* @param fields - An array of field names to check for uniqueness.
|
|
102
|
+
* @returns A validation function that returns true if the value is unique across the specified fields.
|
|
103
|
+
* @throws {Error} When fields is not a non-empty array of strings.
|
|
104
|
+
*/
|
|
25
105
|
isUnique<T extends {
|
|
26
106
|
constructor: {
|
|
27
|
-
exists: (query:
|
|
107
|
+
exists: (query: {
|
|
108
|
+
[key: string]: unknown;
|
|
109
|
+
}) => Promise<unknown>;
|
|
28
110
|
};
|
|
29
111
|
}>(fields: string[]): (this: T, value: unknown) => Promise<boolean>;
|
|
112
|
+
/**
|
|
113
|
+
* Creates a regex pattern validator.
|
|
114
|
+
* This function returns a validator that checks if a string value matches
|
|
115
|
+
* all provided regular expressions.
|
|
116
|
+
*
|
|
117
|
+
* @param regexArray - An array of regular expressions to test against the value.
|
|
118
|
+
* @returns A validation function that returns true if the value matches all regex patterns.
|
|
119
|
+
* @throws {Error} When regexArray is not an array of valid RegExp objects.
|
|
120
|
+
*/
|
|
30
121
|
matchesRegex(regexArray: RegExp[]): (value: string) => Promise<boolean>;
|
|
31
122
|
};
|
|
123
|
+
/**
|
|
124
|
+
* Migration utilities for MongoDB.
|
|
125
|
+
* This object extends the migrate-mongo library with additional configuration utilities.
|
|
126
|
+
*/
|
|
32
127
|
migrate: {
|
|
128
|
+
/**
|
|
129
|
+
* Sets the migration configuration and updates .gitignore.
|
|
130
|
+
* This function creates a migration configuration file and ensures it's properly
|
|
131
|
+
* excluded from version control.
|
|
132
|
+
*
|
|
133
|
+
* @param options - Migration configuration options to write to the config file.
|
|
134
|
+
*/
|
|
33
135
|
setConfig: (options: Partial<migrate.config.Config>) => void;
|
|
34
136
|
init(): Promise<void>;
|
|
35
137
|
create(description: string): Promise<string>;
|
|
36
|
-
up(db:
|
|
37
|
-
down(db:
|
|
38
|
-
status(db:
|
|
138
|
+
up(db: import('mongodb').Db, client: import('mongodb').MongoClient): Promise<string[]>;
|
|
139
|
+
down(db: import('mongodb').Db, client: import('mongodb').MongoClient): Promise<string[]>;
|
|
140
|
+
status(db: import('mongodb').Db): Promise<migrate.MigrationStatus[]>;
|
|
39
141
|
database: typeof migrate.database;
|
|
40
142
|
config: typeof migrate.config;
|
|
41
143
|
};
|
|
144
|
+
/**
|
|
145
|
+
* Converts string values in a filter to regex patterns for case-insensitive search.
|
|
146
|
+
* This function recursively processes a filter object and converts string values in specified fields
|
|
147
|
+
* to MongoDB regex patterns that support accented character matching.
|
|
148
|
+
*
|
|
149
|
+
* @param filter - The filter object to process.
|
|
150
|
+
* @param fields - An array of field names to convert to regex patterns.
|
|
151
|
+
* @returns A new filter object with string values converted to regex patterns.
|
|
152
|
+
*/
|
|
42
153
|
regexify<T>(filter?: T_FilterQuery<T>, fields?: (keyof T | string)[]): T_FilterQuery<T>;
|
|
154
|
+
/**
|
|
155
|
+
* Checks if a virtual options object has a dynamic ref function.
|
|
156
|
+
*
|
|
157
|
+
* @param options - The virtual options to check.
|
|
158
|
+
* @returns True if the options contain a dynamic ref function.
|
|
159
|
+
*/
|
|
160
|
+
isDynamicVirtual<T, R extends string = string>(options?: T_VirtualOptions<T, R>): options is I_DynamicVirtualOptions<T, R>;
|
|
43
161
|
};
|
|
162
|
+
/**
|
|
163
|
+
* MongoDB native driver controller for direct database operations.
|
|
164
|
+
* This class provides a simplified interface for MongoDB operations using the native driver,
|
|
165
|
+
* with automatic generic field generation and standardized response formatting.
|
|
166
|
+
*/
|
|
44
167
|
export declare class MongoController<D extends Partial<C_Document>> {
|
|
45
168
|
private collection;
|
|
169
|
+
/**
|
|
170
|
+
* Creates a new MongoDB controller instance.
|
|
171
|
+
*
|
|
172
|
+
* @param db - The MongoDB database instance.
|
|
173
|
+
* @param collectionName - The name of the collection to operate on.
|
|
174
|
+
*/
|
|
46
175
|
constructor(db: C_Db, collectionName: string);
|
|
176
|
+
/**
|
|
177
|
+
* Creates a single document in the collection.
|
|
178
|
+
* This method adds generic fields (id, isDel, timestamps) to the document before insertion.
|
|
179
|
+
*
|
|
180
|
+
* @param document - The document to create, with or without generic fields.
|
|
181
|
+
* @returns A promise that resolves to a standardized response with the created document.
|
|
182
|
+
*/
|
|
47
183
|
createOne(document: D | Partial<D>): Promise<I_Return<D | Partial<D>>>;
|
|
184
|
+
/**
|
|
185
|
+
* Creates multiple documents in the collection.
|
|
186
|
+
* This method adds generic fields to each document before bulk insertion.
|
|
187
|
+
*
|
|
188
|
+
* @param documents - An array of documents to create.
|
|
189
|
+
* @returns A promise that resolves to a standardized response with the created documents.
|
|
190
|
+
*/
|
|
48
191
|
createMany(documents: (D | Partial<D>)[]): Promise<I_Return<(D | Partial<D>)[]>>;
|
|
192
|
+
/**
|
|
193
|
+
* Finds a single document by filter criteria.
|
|
194
|
+
*
|
|
195
|
+
* @param filter - The filter criteria to find the document.
|
|
196
|
+
* @returns A promise that resolves to a standardized response with the found document.
|
|
197
|
+
*/
|
|
49
198
|
findOne(filter: T_Filter<D>): Promise<I_Return<T_WithId<D>>>;
|
|
199
|
+
/**
|
|
200
|
+
* Finds all documents matching the filter criteria.
|
|
201
|
+
*
|
|
202
|
+
* @param filter - The filter criteria to find documents (defaults to empty object for all documents).
|
|
203
|
+
* @returns A promise that resolves to a standardized response with the found documents.
|
|
204
|
+
*/
|
|
50
205
|
findAll(filter?: T_Filter<D>): Promise<I_Return<T_WithId<D>[]>>;
|
|
206
|
+
/**
|
|
207
|
+
* Counts documents matching the filter criteria.
|
|
208
|
+
*
|
|
209
|
+
* @param filter - The filter criteria to count documents (defaults to empty object for all documents).
|
|
210
|
+
* @returns A promise that resolves to a standardized response with the document count.
|
|
211
|
+
*/
|
|
51
212
|
count(filter?: T_Filter<D>): Promise<I_Return<number>>;
|
|
213
|
+
/**
|
|
214
|
+
* Updates a single document matching the filter criteria.
|
|
215
|
+
*
|
|
216
|
+
* @param filter - The filter criteria to find the document to update.
|
|
217
|
+
* @param update - The update data to apply to the document.
|
|
218
|
+
* @returns A promise that resolves to a standardized response with the update result.
|
|
219
|
+
*/
|
|
52
220
|
updateOne(filter: T_Filter<D>, update: Partial<D>): Promise<I_Return<T_UpdateResult>>;
|
|
221
|
+
/**
|
|
222
|
+
* Updates multiple documents matching the filter criteria.
|
|
223
|
+
*
|
|
224
|
+
* @param filter - The filter criteria to find documents to update.
|
|
225
|
+
* @param update - The update data to apply to the documents.
|
|
226
|
+
* @returns A promise that resolves to a standardized response with the update result.
|
|
227
|
+
*/
|
|
53
228
|
updateMany(filter: T_Filter<D>, update: Partial<D>): Promise<I_Return<T_UpdateResult>>;
|
|
229
|
+
/**
|
|
230
|
+
* Deletes a single document matching the filter criteria.
|
|
231
|
+
*
|
|
232
|
+
* @param filter - The filter criteria to find the document to delete.
|
|
233
|
+
* @returns A promise that resolves to a standardized response with the delete result.
|
|
234
|
+
*/
|
|
54
235
|
deleteOne(filter: T_Filter<D>): Promise<I_Return<T_DeleteResult>>;
|
|
236
|
+
/**
|
|
237
|
+
* Deletes multiple documents matching the filter criteria.
|
|
238
|
+
*
|
|
239
|
+
* @param filter - The filter criteria to find documents to delete.
|
|
240
|
+
* @returns A promise that resolves to a standardized response with the delete result.
|
|
241
|
+
*/
|
|
55
242
|
deleteMany(filter: T_Filter<D>): Promise<I_Return<T_DeleteResult>>;
|
|
56
243
|
}
|
|
244
|
+
/**
|
|
245
|
+
* Mongoose controller for database operations with advanced features.
|
|
246
|
+
* This class provides a comprehensive interface for Mongoose operations including
|
|
247
|
+
* pagination, aggregation, slug generation, and short ID creation.
|
|
248
|
+
*/
|
|
57
249
|
export declare class MongooseController<T extends Partial<C_Document>> {
|
|
58
250
|
private model;
|
|
251
|
+
/**
|
|
252
|
+
* Creates a new Mongoose controller instance.
|
|
253
|
+
*
|
|
254
|
+
* @param model - The Mongoose model to operate on.
|
|
255
|
+
*/
|
|
59
256
|
constructor(model: I_ExtendedModel<T>);
|
|
257
|
+
/**
|
|
258
|
+
* Gets the model name for logging and error messages.
|
|
259
|
+
*
|
|
260
|
+
* @returns The name of the model.
|
|
261
|
+
*/
|
|
60
262
|
private getModelName;
|
|
263
|
+
/**
|
|
264
|
+
* Finds a single document with optional population and projection.
|
|
265
|
+
* Automatically handles dynamic virtual population if configured.
|
|
266
|
+
*
|
|
267
|
+
* @param filter - The filter criteria to find the document.
|
|
268
|
+
* @param projection - The fields to include/exclude in the result.
|
|
269
|
+
* @param options - Query options for the operation.
|
|
270
|
+
* @param populate - Population configuration for related documents.
|
|
271
|
+
* @returns A promise that resolves to a standardized response with the found document.
|
|
272
|
+
*/
|
|
61
273
|
findOne(filter?: T_FilterQuery<T>, projection?: T_ProjectionType<T>, options?: T_QueryOptions<T>, populate?: T_Input_Populate): Promise<I_Return<T>>;
|
|
274
|
+
/**
|
|
275
|
+
* Finds all documents with optional population and projection.
|
|
276
|
+
* Automatically handles dynamic virtual population if configured.
|
|
277
|
+
*
|
|
278
|
+
* @param filter - The filter criteria to find documents.
|
|
279
|
+
* @param projection - The fields to include/exclude in the result.
|
|
280
|
+
* @param options - Query options for the operation.
|
|
281
|
+
* @param populate - Population configuration for related documents.
|
|
282
|
+
* @returns A promise that resolves to a standardized response with the found documents.
|
|
283
|
+
*/
|
|
62
284
|
findAll(filter?: T_FilterQuery<T>, projection?: T_ProjectionType<T>, options?: T_QueryOptions<T>, populate?: T_Input_Populate): Promise<I_Return<T[]>>;
|
|
63
|
-
|
|
64
|
-
|
|
285
|
+
/**
|
|
286
|
+
* Finds documents with pagination support.
|
|
287
|
+
* Automatically handles dynamic virtual population if configured.
|
|
288
|
+
*
|
|
289
|
+
* @param filter - The filter criteria to find documents.
|
|
290
|
+
* @param options - Pagination options including page, limit, and population.
|
|
291
|
+
* @returns A promise that resolves to a standardized response with paginated results.
|
|
292
|
+
*/
|
|
293
|
+
findPaging(filter?: T_FilterQuery<T>, options?: I_PaginateOptionsWithPopulate): Promise<I_Return<T_PaginateResult<T>>>;
|
|
294
|
+
/**
|
|
295
|
+
* Performs aggregation with pagination support.
|
|
296
|
+
*
|
|
297
|
+
* @param pipeline - The aggregation pipeline stages.
|
|
298
|
+
* @param options - Pagination options for the aggregation result.
|
|
299
|
+
* @returns A promise that resolves to a standardized response with paginated aggregation results.
|
|
300
|
+
*/
|
|
301
|
+
findPagingAggregate(pipeline: T_PipelineStage[], options?: I_PaginateOptionsWithPopulate): Promise<I_Return<T_AggregatePaginateResult<T>>>;
|
|
302
|
+
/**
|
|
303
|
+
* Counts documents matching the filter criteria.
|
|
304
|
+
*
|
|
305
|
+
* @param filter - The filter criteria to count documents.
|
|
306
|
+
* @returns A promise that resolves to a standardized response with the document count.
|
|
307
|
+
*/
|
|
65
308
|
count(filter?: T_FilterQuery<T>): Promise<I_Return<number>>;
|
|
309
|
+
/**
|
|
310
|
+
* Creates a single document.
|
|
311
|
+
*
|
|
312
|
+
* @param doc - The document to create.
|
|
313
|
+
* @returns A promise that resolves to a standardized response with the created document.
|
|
314
|
+
*/
|
|
66
315
|
createOne(doc: T | Partial<T>): Promise<I_Return<T>>;
|
|
316
|
+
/**
|
|
317
|
+
* Creates multiple documents with bulk insertion.
|
|
318
|
+
*
|
|
319
|
+
* @param docs - An array of documents to create.
|
|
320
|
+
* @param options - Options for the bulk insertion operation.
|
|
321
|
+
* @returns A promise that resolves to a standardized response with the created documents.
|
|
322
|
+
*/
|
|
67
323
|
createMany(docs: (T | Partial<T>)[], options?: T_InsertManyOptions): Promise<I_Return<T[]>>;
|
|
324
|
+
/**
|
|
325
|
+
* Updates a single document and returns the updated version.
|
|
326
|
+
*
|
|
327
|
+
* @param filter - The filter criteria to find the document to update.
|
|
328
|
+
* @param update - The update data to apply.
|
|
329
|
+
* @param options - Options for the update operation.
|
|
330
|
+
* @returns A promise that resolves to a standardized response with the updated document.
|
|
331
|
+
*/
|
|
68
332
|
updateOne(filter?: T_FilterQuery<T>, update?: T_UpdateQuery<T>, options?: I_UpdateOptionsExtended): Promise<I_Return<T>>;
|
|
333
|
+
/**
|
|
334
|
+
* Updates multiple documents matching the filter criteria.
|
|
335
|
+
*
|
|
336
|
+
* @param filter - The filter criteria to find documents to update.
|
|
337
|
+
* @param update - The update data to apply.
|
|
338
|
+
* @param options - Options for the update operation.
|
|
339
|
+
* @returns A promise that resolves to a standardized response with the update result.
|
|
340
|
+
*/
|
|
69
341
|
updateMany(filter?: T_FilterQuery<T>, update?: T_UpdateQuery<T>, options?: I_UpdateOptionsExtended): Promise<I_Return<T_UpdateResult>>;
|
|
342
|
+
/**
|
|
343
|
+
* Deletes a single document and returns the deleted version.
|
|
344
|
+
*
|
|
345
|
+
* @param filter - The filter criteria to find the document to delete.
|
|
346
|
+
* @param options - Options for the delete operation.
|
|
347
|
+
* @returns A promise that resolves to a standardized response with the deleted document.
|
|
348
|
+
*/
|
|
70
349
|
deleteOne(filter?: T_FilterQuery<T>, options?: I_DeleteOptionsExtended): Promise<I_Return<T>>;
|
|
350
|
+
/**
|
|
351
|
+
* Deletes multiple documents matching the filter criteria.
|
|
352
|
+
*
|
|
353
|
+
* @param filter - The filter criteria to find documents to delete.
|
|
354
|
+
* @param options - Options for the delete operation.
|
|
355
|
+
* @returns A promise that resolves to a standardized response with the delete result.
|
|
356
|
+
*/
|
|
71
357
|
deleteMany(filter?: T_FilterQuery<T>, options?: I_DeleteOptionsExtended): Promise<I_Return<T_DeleteResult>>;
|
|
358
|
+
/**
|
|
359
|
+
* Creates a unique short ID based on a given ID.
|
|
360
|
+
* This method generates multiple short IDs with increasing lengths and finds the first available one.
|
|
361
|
+
*
|
|
362
|
+
* @param id - The base ID to generate short IDs from.
|
|
363
|
+
* @param length - The initial length for short ID generation (default: 4).
|
|
364
|
+
* @returns A promise that resolves to a standardized response with the unique short ID.
|
|
365
|
+
*/
|
|
72
366
|
createShortId(id: string, length?: number): Promise<I_Return<string>>;
|
|
367
|
+
/**
|
|
368
|
+
* Creates a query for slug existence checking.
|
|
369
|
+
* This method generates a query that checks for slug existence in both current and historical slug fields.
|
|
370
|
+
*
|
|
371
|
+
* @param options - Configuration for slug query generation including slug, field, and filter.
|
|
372
|
+
* @param options.slug - The slug string to check for existence.
|
|
373
|
+
* @param options.field - The field name for object-based slug checking.
|
|
374
|
+
* @param options.isObject - Whether the slug is stored as an object with nested fields.
|
|
375
|
+
* @param options.filter - Additional filter conditions to apply to the query.
|
|
376
|
+
* @returns A MongoDB query object for checking slug existence.
|
|
377
|
+
*/
|
|
73
378
|
createSlugQuery({ slug, field, isObject, filter }: I_Input_GenerateSlug<T>): {
|
|
74
379
|
$or: ({
|
|
75
380
|
[x: string]: string;
|
|
@@ -226,8 +531,46 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
226
531
|
$comment?: string;
|
|
227
532
|
$expr?: Record<string, any>;
|
|
228
533
|
};
|
|
534
|
+
/**
|
|
535
|
+
* Creates a unique slug based on a given string.
|
|
536
|
+
* This method generates multiple slug variations and finds the first available one.
|
|
537
|
+
*
|
|
538
|
+
* @param options - Configuration for slug generation including slug, field, and filter.
|
|
539
|
+
* @param options.slug - The base slug string to make unique.
|
|
540
|
+
* @param options.field - The field name for object-based slug checking.
|
|
541
|
+
* @param options.isObject - Whether the slug is stored as an object with nested fields.
|
|
542
|
+
* @param options.filter - Additional filter conditions to apply when checking slug existence.
|
|
543
|
+
* @returns A promise that resolves to a unique slug string.
|
|
544
|
+
*/
|
|
229
545
|
createUniqueSlug({ slug, field, isObject, filter }: I_Input_GenerateSlug<T>): Promise<string>;
|
|
546
|
+
/**
|
|
547
|
+
* Creates a slug for a document field.
|
|
548
|
+
* This method handles both simple string fields and object fields with nested slug generation.
|
|
549
|
+
*
|
|
550
|
+
* @param options - Configuration for slug creation including field, source document, and filter.
|
|
551
|
+
* @param options.field - The field name to create a slug for.
|
|
552
|
+
* @param options.from - The source document containing the field value.
|
|
553
|
+
* @param options.filter - Additional filter conditions to apply when checking slug existence.
|
|
554
|
+
* @returns A promise that resolves to a standardized response with the created slug(s).
|
|
555
|
+
*/
|
|
230
556
|
createSlug<R = string>({ field, from, filter }: I_Input_CreateSlug<T>): Promise<I_Return<R>>;
|
|
557
|
+
/**
|
|
558
|
+
* Checks if a slug already exists in the collection.
|
|
559
|
+
* This method verifies slug existence in both current and historical slug fields.
|
|
560
|
+
*
|
|
561
|
+
* @param options - Configuration for slug checking including slug, field, source document, and filter.
|
|
562
|
+
* @param options.slug - The slug string to check for existence.
|
|
563
|
+
* @param options.field - The field name for object-based slug checking.
|
|
564
|
+
* @param options.from - The source document containing the field value.
|
|
565
|
+
* @param options.filter - Additional filter conditions to apply to the query.
|
|
566
|
+
* @returns A promise that resolves to a standardized response indicating whether the slug exists.
|
|
567
|
+
*/
|
|
231
568
|
checkSlug({ slug, field, from, filter }: I_Input_CheckSlug<T>): Promise<I_Return<boolean>>;
|
|
569
|
+
/**
|
|
570
|
+
* Performs aggregation operations on the collection.
|
|
571
|
+
*
|
|
572
|
+
* @param pipeline - The aggregation pipeline stages to execute.
|
|
573
|
+
* @returns A promise that resolves to a standardized response with the aggregation results.
|
|
574
|
+
*/
|
|
232
575
|
aggregate(pipeline: T_PipelineStage[]): Promise<I_Return<T[]>>;
|
|
233
576
|
}
|