@cyberskill/shared 2.6.0 → 2.8.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/dist/node/mongo/index.cjs +1 -1
- package/dist/node/mongo/index.js +11 -10
- package/dist/node/mongo/mongo.constant.cjs +1 -1
- package/dist/node/mongo/mongo.constant.d.ts +6 -0
- package/dist/node/mongo/mongo.constant.js +3 -2
- package/dist/node/mongo/mongo.type.d.ts +2 -0
- package/dist/node/mongo/mongo.util.cjs +5 -5
- package/dist/node/mongo/mongo.util.d.ts +13 -4
- package/dist/node/mongo/mongo.util.js +271 -245
- package/dist/util/object/object.util.cjs +1 -1
- package/dist/util/object/object.util.d.ts +8 -3
- package/dist/util/object/object.util.js +51 -45
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./mongo.constant.cjs"),o=require("./mongo.type.cjs"),e=require("./mongo.util.cjs");exports.MONGO_MIGRATE_OPTIONS=n.MONGO_MIGRATE_OPTIONS;exports.C_Collection=o.C_Collection;exports.C_Db=o.C_Db;exports.C_Document=o.C_Document;exports.C_Model=o.C_Model;exports.MongoController=e.MongoController;exports.MongooseController=e.MongooseController;exports.mongo=e.mongo;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./mongo.constant.cjs"),o=require("./mongo.type.cjs"),e=require("./mongo.util.cjs");exports.MONGO_MIGRATE_OPTIONS=n.MONGO_MIGRATE_OPTIONS;exports.MONGO_SLUG_MAX_ATTEMPTS=n.MONGO_SLUG_MAX_ATTEMPTS;exports.C_Collection=o.C_Collection;exports.C_Db=o.C_Db;exports.C_Document=o.C_Document;exports.C_Model=o.C_Model;exports.MongoController=e.MongoController;exports.MongooseController=e.MongooseController;exports.mongo=e.mongo;
|
package/dist/node/mongo/index.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { MONGO_MIGRATE_OPTIONS as e } from "./mongo.constant.js";
|
|
2
|
-
import { C_Collection as
|
|
3
|
-
import { MongoController as
|
|
1
|
+
import { MONGO_MIGRATE_OPTIONS as e, MONGO_SLUG_MAX_ATTEMPTS as _ } from "./mongo.constant.js";
|
|
2
|
+
import { C_Collection as l, C_Db as n, C_Document as t, C_Model as C } from "./mongo.type.js";
|
|
3
|
+
import { MongoController as m, MongooseController as T, mongo as G } from "./mongo.util.js";
|
|
4
4
|
export {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
l as C_Collection,
|
|
6
|
+
n as C_Db,
|
|
7
|
+
t as C_Document,
|
|
8
|
+
C as C_Model,
|
|
9
9
|
e as MONGO_MIGRATE_OPTIONS,
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
_ as MONGO_SLUG_MAX_ATTEMPTS,
|
|
11
|
+
m as MongoController,
|
|
12
|
+
T as MongooseController,
|
|
13
|
+
G as mongo
|
|
13
14
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O="MONGO_MIGRATE_OPTIONS";exports.MONGO_MIGRATE_OPTIONS=O;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O="MONGO_MIGRATE_OPTIONS",M=100;exports.MONGO_MIGRATE_OPTIONS=O;exports.MONGO_SLUG_MAX_ATTEMPTS=M;
|
|
@@ -4,3 +4,9 @@
|
|
|
4
4
|
* MongoDB migration settings and options for database schema management.
|
|
5
5
|
*/
|
|
6
6
|
export declare const MONGO_MIGRATE_OPTIONS = "MONGO_MIGRATE_OPTIONS";
|
|
7
|
+
/**
|
|
8
|
+
* Maximum number of attempts to generate a unique slug.
|
|
9
|
+
* This constant defines the maximum number of attempts to generate a unique slug
|
|
10
|
+
* before giving up and returning a fallback slug.
|
|
11
|
+
*/
|
|
12
|
+
export declare const MONGO_SLUG_MAX_ATTEMPTS = 100;
|
|
@@ -159,6 +159,7 @@ export interface I_Input_DeleteMany<T> {
|
|
|
159
159
|
export interface I_InputSlug<T> {
|
|
160
160
|
field: string;
|
|
161
161
|
filter?: T_FilterQuery<T>;
|
|
162
|
+
haveHistory?: boolean;
|
|
162
163
|
}
|
|
163
164
|
export interface I_Input_CreateSlug<T> extends I_InputSlug<T> {
|
|
164
165
|
from: T;
|
|
@@ -170,5 +171,6 @@ export interface I_Input_CheckSlug<T> extends I_InputSlug<T> {
|
|
|
170
171
|
export interface I_Input_GenerateSlug<T> extends I_InputSlug<T> {
|
|
171
172
|
slug: string;
|
|
172
173
|
isObject: boolean;
|
|
174
|
+
haveHistory?: boolean;
|
|
173
175
|
}
|
|
174
176
|
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("lodash-es"),B=require("migrate-mongo"),
|
|
2
|
-
module.exports = ${JSON.stringify(s,null,4)}`;
|
|
3
|
-
${
|
|
4
|
-
`;
|
|
5
|
-
`).includes(T.MIGRATE_MONGO_CONFIG)||M.appendFileSync(T.PATH.GIT_IGNORE,e):M.writeFileSync(T.PATH.GIT_IGNORE,e)}}),regexify(s,t){if(!s)return{};let e=q.cloneDeep(s);if(!t||t.length===0)return e;for(const r of t){const n=r.toString().split("."),c=N.getNestedValue(e,n);if(typeof c=="string"&&c.length>0){const o={$regex:`.*${W.regexSearchMapper(c)}.*`,$options:"i"};e=N.setNestedValue(e,n,o)}}return e},isDynamicVirtual(s){return!!(s&&typeof s.ref=="function")},getNewRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?t.filter(c=>!r.result.some(o=>e(o,c))):t})},getExistingRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?r.result.filter(c=>t.some(o=>e(c,o))):[]})}};function ne(s){return s!==null&&typeof s=="object"&&"toObject"in s&&typeof s.toObject=="function"}function I(s,t){if(!s||!t||t.length===0)return s;const e=new Set(t.map(r=>r.name));if(Array.isArray(s)){const r=s.filter(n=>{if(typeof n=="string")return!e.has(n);if(typeof n=="object"&&n!==null){const c=n;return!e.has(c.path||c.populate||"")}return!0});return r.length>0?r:void 0}if(typeof s=="string")return e.has(s)?void 0:s;if(typeof s=="object"&&s!==null){const r=s,n=r.path||r.populate||"";return e.has(n)?void 0:s}return s}function se(s,t,e){if(!s.length||!t||!(e!=null&&e.ref))return[];const r=new Map;return s.forEach(n=>{try{const c=e.ref(n);if(c==null)return;const o=typeof c=="string"?c:String(c);if(o&&o.trim()!==""){const i=re(o);r.has(i)||r.set(i,[]),r.get(i).push(n)}}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(([n,c])=>({model:n,docs:c}))}function z(s,t,e,r,n){return l(this,null,function*(){if(!t.length||!e.length||!r)return t;const c=e.filter(u=>{if(Array.isArray(r))return r.length>0&&r.some(a=>typeof a=="string"?a===u.name:a.path===u.name);if(typeof r=="string")return r===u.name;if(typeof r=="object"&&r!==null){const a=r;return a.path&&a.path===u.name||a.populate&&a.populate===u.name}return!1});if(c.length===0)return t;const o=q.cloneDeep(t.map(u=>ne(u)?u.toObject():u));o.forEach(u=>{c.forEach(({name:a,options:d})=>{if(!(a in u)){const h=u;h[a]=d.count?0:d.justOne?null:[]}})});const i=new Map;for(const u of c){const{name:a,options:d}=u,h=se(o,a,d);for(const E of h){i.has(E.model)||i.set(E.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const m=i.get(E.model);m.virtuals.find(V=>V.name===a)||(m.virtuals.push(u),m.localValueSets.set(a,new Set));const b=m.localValueSets.get(a);E.docs.forEach(V=>{const x=V[d.localField];if(x!=null){const _=String(x);b.add(_);let R=-1;const v=V;v.id!==void 0?R=o.findIndex(F=>F.id===v.id):v._id!==void 0&&(R=o.findIndex(F=>{var S,g,p,y;return((g=(S=F._id)==null?void 0:S.toString)==null?void 0:g.call(S))===((y=(p=v._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(i.entries()).map(u=>l(null,[u],function*([a,d]){const h=s.models[a];if(!h)return;const E=new Set;if(d.localValueSets.forEach(_=>{_.forEach(R=>E.add(R))}),E.size===0)return;const m=[...new Set(d.virtuals.map(_=>_.options.foreignField))],b=Array.from(E);let V;m.length===1?V={[String(m[0])]:{$in:b}}:V={$or:m.map(_=>({[_]:{$in:b}}))};const x=yield h.find(V,n).lean();for(const _ of d.virtuals){const{name:R,options:v}=_,F=x.filter(S=>{const g=S[v.foreignField];return g!=null&&E.has(String(g))});if(v.count){const S=new Map;F.forEach(g=>{var p;const y=(p=g[v.foreignField])==null?void 0:p.toString();y&&S.set(y,(S.get(y)||0)+1)}),d.localValueSets.get(R).forEach(g=>{const p=d.docsByLocalValue.get(g)||[],y=S.get(g)||0;p.forEach(w=>{const C=o[w];C[R]===void 0&&(C[R]=y)})})}else{const S=new Map;F.forEach(g=>{var p;const y=(p=g[v.foreignField])==null?void 0:p.toString();y&&(S.has(y)||S.set(y,[]),S.get(y).push(g))}),d.localValueSets.get(R).forEach(g=>{const p=d.docsByLocalValue.get(g)||[],y=S.get(g)||[],w=v.justOne?y[0]||null:y;p.forEach(C=>{const L=o[C];L[R]=w})})}}}))),o})}class ce{constructor(t,e){te(this,"collection"),this.collection=t.collection(e)}createOne(t){return l(this,null,function*(){try{const e=O(O({},A.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 f.catchError(e)}})}createMany(t){return l(this,null,function*(){try{const e=t.map(n=>O(O({},A.createGenericFields()),n)),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 f.catchError(e)}})}findOne(t){return l(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 f.catchError(e)}})}findAll(){return l(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 l(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 l(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 f.catchError(r)}})}updateMany(t,e){return l(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 f.catchError(r)}})}deleteOne(t){return l(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 f.catchError(e)}})}deleteMany(t){return l(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 f.catchError(e)}})}}class oe{constructor(t){this.model=t}getModelName(){return this.model.modelName}getDynamicVirtuals(){return this.model.schema.statics._dynamicVirtuals}populateDynamicVirtualsForDocument(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();if(r&&r.length>0){const n=yield z(this.model.base,[t],r,e);return n&&n[0]?n[0]:t}return t})}populateDynamicVirtualsForDocuments(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();return r&&r.length>0&&t.length>0?yield z(this.model.base,t,r,e):t})}findOne(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=N.normalizeMongoFilter(t),o=this.model.findOne(c,e,r),i=this.getDynamicVirtuals(),u=I(n,i);u&&o.populate(u);const a=yield o.exec();return a?{success:!0,result:yield this.populateDynamicVirtualsForDocument(a,n)}:{success:!1,message:`No ${this.getModelName()} found.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(c){return f.catchError(c)}})}findAll(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=N.normalizeMongoFilter(t),o=this.model.find(c,e,r),i=this.getDynamicVirtuals(),u=I(n,i);u&&o.populate(u);const a=yield o.exec();return{success:!0,result:yield this.populateDynamicVirtualsForDocuments(a,n)}}catch(c){return f.catchError(c)}})}findPaging(){return l(this,arguments,function*(t={},e={}){try{const r=N.normalizeMongoFilter(t),n=this.getDynamicVirtuals(),c=O({},e);e.populate&&(c.populate=I(e.populate,n));const o=yield this.model.paginate(r,c),i=yield this.populateDynamicVirtualsForDocuments(o.docs,e.populate);return{success:!0,result:P(O({},o),{docs:i})}}catch(r){return f.catchError(r)}})}findPagingAggregate(t){return l(this,arguments,function*(e,r={}){try{const n=this.getDynamicVirtuals(),c=O({},r);r.populate&&(c.populate=I(r.populate,n));const o=yield this.model.aggregatePaginate(this.model.aggregate(e),c),i=yield this.populateDynamicVirtualsForDocuments(o.docs,r.populate);return{success:!0,result:P(O({},o),{docs:i})}}catch(n){return f.catchError(n)}})}count(){return l(this,arguments,function*(t={}){try{const e=N.normalizeMongoFilter(t);return{success:!0,result:yield this.model.countDocuments(e)}}catch(e){return f.catchError(e)}})}createOne(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.create(t)}}catch(e){return f.catchError(e)}})}createMany(t){return l(this,arguments,function*(e,r={}){try{return{success:!0,result:(yield this.model.insertMany(e,r)).map(o=>o instanceof H.Document?o.toObject():null).filter(o=>o!==null)}}catch(n){return f.catchError(n)}})}updateOne(){return l(this,arguments,function*(t={},e={},r={}){try{const n=N.normalizeMongoFilter(t),c=yield this.model.findOneAndUpdate(n,e,O({new:!0},r)).exec();return c?{success:!0,result:c}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(n){return f.catchError(n)}})}updateMany(){return l(this,arguments,function*(t={},e={},r={}){try{const n=N.normalizeMongoFilter(t);return{success:!0,result:yield this.model.updateMany(n,e,r).exec()}}catch(n){return f.catchError(n)}})}deleteOne(){return l(this,arguments,function*(t={},e={}){try{const r=N.normalizeMongoFilter(t),n=yield this.model.findOneAndDelete(r,e).exec();return n?{success:!0,result:n}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return f.catchError(r)}})}deleteMany(){return l(this,arguments,function*(t={},e={}){try{const r=N.normalizeMongoFilter(t),n=yield this.model.deleteMany(r,e).exec();return n.deletedCount===0?{success:!1,message:"No documents found to delete.",code:D.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:n}}catch(r){return f.catchError(r)}})}createShortId(t,e=4){return l(this,null,function*(){try{const n=Array.from({length:10},(i,u)=>j.generateShortId(t,u+e)),o=(yield Promise.all(n.map(i=>this.model.exists({shortId:i})))).findIndex(i=>!i);if(o!==-1){const i=n[o];if(i)return{success:!0,result:i}}return{success:!1,message:"Failed to create a unique shortId",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return f.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,filter:n}){const c=O({},n!=null?n:{});return r?P(O({},c),{$or:[{[`slug.${e}`]:t},{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]}):P(O({},c),{$or:[{slug:t},{slugHistory:t}]})}createUniqueSlug(t){return l(this,arguments,function*({slug:e,field:r,isObject:n,filter:c}){const o=j.generateSlug(e),u=Array.from({length:100},(h,E)=>E===0?o:`${o}-${E}`),d=(yield Promise.all(u.map(h=>this.model.exists(this.createSlugQuery({slug:h,field:r,isObject:n,filter:c}))))).findIndex(h=>!h);if(d!==-1){const h=u[d];if(h)return h}return`${o}-${Date.now()}`})}createSlug(t){return l(this,arguments,function*({field:e,from:r,filter:n}){try{const c=r[e];return q.isObject(c)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(c).map(a=>l(this,[a],function*([d,h]){const E=yield this.createUniqueSlug({slug:h,field:d,isObject:!0,filter:n});return[d,E]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:c,field:e,isObject:!1,filter:n})}}catch(c){return f.catchError(c)}})}checkSlug(t){return l(this,arguments,function*({slug:e,field:r,from:n,filter:c}){try{const o=n[r];if(q.isObject(o)){const h=Object.values(o).map(m=>j.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 u=j.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:u,field:r,isObject:!1,filter:c})))!==null}}catch(o){return f.catchError(o)}})}aggregate(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return f.catchError(e)}})}}exports.MongoController=ce;exports.MongooseController=oe;exports.mongo=A;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("lodash-es"),B=require("migrate-mongo"),K=require("mongoose"),Q=require("mongoose-aggregate-paginate-v2"),W=require("mongoose-paginate-v2"),$=require("uuid"),H=require("./mongo.constant.cjs"),V=require("../../util/object/object.util.cjs"),k=require("../../util/common/common.util.cjs"),F=require("../fs/fs.util.cjs"),A=require("../path/path.constant.cjs"),J=require("../../util/validate/validate.util.cjs"),j=require("../../util/string/string.util.cjs"),D=require("../../constant/response-status.cjs"),d=require("../log/log.util.cjs");var X=Object.defineProperty,Y=Object.defineProperties,Z=Object.getOwnPropertyDescriptors,G=Object.getOwnPropertySymbols,ee=Object.prototype.hasOwnProperty,te=Object.prototype.propertyIsEnumerable,U=(s,t,e)=>t in s?X(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,O=(s,t)=>{for(var e in t||(t={}))ee.call(t,e)&&U(s,e,t[e]);if(G)for(var e of G(t))te.call(t,e)&&U(s,e,t[e]);return s},P=(s,t)=>Y(s,Z(t)),re=(s,t,e)=>U(s,typeof t!="symbol"?t+"":t,e),l=(s,t,e)=>new Promise((r,n)=>{var c=i=>{try{u(e.next(i))}catch(a){n(a)}},o=i=>{try{u(e.throw(i))}catch(a){n(a)}},u=i=>i.done?r(i.value):Promise.resolve(i.value).then(c,o);u((e=e.apply(s,t)).next())});function ne(s){return s===s.toUpperCase()?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():s}const M={createGenericFields(){return{id:$.v4(),isDel:!1,createdAt:new Date,updatedAt:new Date}},applyPlugins(s,t){t.filter(e=>typeof e=="function").forEach(e=>s.plugin(e))},applyMiddlewares(s,t){t.forEach(({method:e,pre:r,post:n})=>{e&&r&&s.pre(e,r),e&&n&&s.post(e,n)})},createGenericSchema(s){return new s.Schema({id:{type:String,default:$.v4,unique:!0},isDel:{type:Boolean,default:!1}},{timestamps:!0})},createSchema({mongoose:s,schema:t,virtuals:e=[],standalone:r=!1}){const n=new s.Schema(t,{toJSON:{virtuals:!0},toObject:{virtuals:!0}});return e.forEach(({name:c,options:o,get:u})=>{if(M.isDynamicVirtual(o)){const i=n.statics;i._dynamicVirtuals||(i._dynamicVirtuals=[]),i._dynamicVirtuals.push({name:c,options:o});const a=n.virtual(c);u?a.get(u):a.get(function(){var f;return((f=this._populated)==null?void 0:f[c])||(o!=null&&o.count?0:o!=null&&o.justOne?null:[])})}else{const i=n.virtual(c,o);u&&i.get(u)}}),r||n.add(M.createGenericSchema(s)),n},createModel({mongoose:s,name:t,schema:e,virtuals:r=[],pagination:n=!0,aggregate:c=!0,middlewares:o=[]}){if(!t)throw new Error("Model name is required.");if(s.models[t])return s.models[t];const u=M.createSchema({mongoose:s,schema:e,virtuals:r});return(n||c)&&M.applyPlugins(u,[n&&W,c&&Q]),M.applyMiddlewares(u,o),s.model(t,u)},validator:{isRequired(){return function(s){return l(this,null,function*(){return!J.validate.isEmpty(s)})}},isUnique(s){return function(t){return l(this,null,function*(){if(!Array.isArray(s)||s.length===0)throw new Error("Fields must be a non-empty array of strings.");const e={$or:s.map(n=>({[n]:t}))};return!(yield this.constructor.exists(e))})}},matchesRegex(s){return function(t){return l(this,null,function*(){if(!Array.isArray(s)||s.some(e=>!(e instanceof RegExp)))throw new Error("regexArray must be an array of valid RegExp objects.");return s.every(e=>e.test(t))})}}},migrate:P(O({},B),{setConfig:s=>{const t=`// This file is automatically generated by the Cyberskill CLI.
|
|
2
|
+
module.exports = ${JSON.stringify(s,null,4)}`;F.writeFileSync(A.PATH.MIGRATE_MONGO_CONFIG,t);const e=`
|
|
3
|
+
${A.MIGRATE_MONGO_CONFIG}
|
|
4
|
+
`;F.pathExistsSync(A.PATH.GIT_IGNORE)?F.readFileSync(A.PATH.GIT_IGNORE,"utf-8").split(`
|
|
5
|
+
`).includes(A.MIGRATE_MONGO_CONFIG)||F.appendFileSync(A.PATH.GIT_IGNORE,e):F.writeFileSync(A.PATH.GIT_IGNORE,e)}}),regexify(s,t){if(!s)return{};let e=q.cloneDeep(s);if(!t||t.length===0)return e;for(const r of t){const n=r.toString().split("."),c=V.getNestedValue(e,n);if(typeof c=="string"&&c.length>0){const o={$regex:`.*${k.regexSearchMapper(c)}.*`,$options:"i"};e=V.setNestedValue(e,n,o)}}return e},isDynamicVirtual(s){return!!(s&&typeof s.ref=="function")},getNewRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?t.filter(c=>!r.result.some(o=>e(o,c))):t})},getExistingRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?r.result.filter(c=>t.some(o=>e(c,o))):[]})}};function se(s){return s!==null&&typeof s=="object"&&"toObject"in s&&typeof s.toObject=="function"}function I(s,t){if(!s||!t||t.length===0)return s;const e=new Set(t.map(r=>r.name));if(Array.isArray(s)){const r=s.filter(n=>{if(typeof n=="string")return!e.has(n);if(typeof n=="object"&&n!==null){const c=n;return!e.has(c.path||c.populate||"")}return!0});return r.length>0?r:void 0}if(typeof s=="string")return e.has(s)?void 0:s;if(typeof s=="object"&&s!==null){const r=s,n=r.path||r.populate||"";return e.has(n)?void 0:s}return s}function ce(s,t,e){if(!s.length||!t||!(e!=null&&e.ref))return[];const r=new Map;return s.forEach(n=>{try{const c=e.ref(n);if(c==null)return;const o=typeof c=="string"?c:String(c);if(o&&o.trim()!==""){const u=ne(o);r.has(u)||r.set(u,[]),r.get(u).push(n)}}catch(c){d.catchError(new Error(`Dynamic ref function failed for virtual "${t}": ${c instanceof Error?c.message:String(c)}`))}}),Array.from(r.entries()).map(([n,c])=>({model:n,docs:c}))}function z(s,t,e,r,n){return l(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(a=>typeof a=="string"?a===i.name:a.path===i.name);if(typeof r=="string")return r===i.name;if(typeof r=="object"&&r!==null){const a=r;return a.path&&a.path===i.name||a.populate&&a.populate===i.name}return!1});if(c.length===0)return t;const o=q.cloneDeep(t.map(i=>se(i)?i.toObject():i));o.forEach(i=>{c.forEach(({name:a,options:f})=>{if(!(a in i)){const S=i;S[a]=f.count?0:f.justOne?null:[]}})});const u=new Map;for(const i of c){const{name:a,options:f}=i,S=ce(o,a,f);for(const h of S){u.has(h.model)||u.set(h.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const y=u.get(h.model);y.virtuals.find(T=>T.name===a)||(y.virtuals.push(i),y.localValueSets.set(a,new Set));const N=y.localValueSets.get(a);h.docs.forEach(T=>{const x=T[f.localField];if(x!=null){const _=String(x);N.add(_);let R=-1;const v=T;v.id!==void 0?R=o.findIndex(b=>b.id===v.id):v._id!==void 0&&(R=o.findIndex(b=>{var E,m,p,g;return((m=(E=b._id)==null?void 0:E.toString)==null?void 0:m.call(E))===((g=(p=v._id)==null?void 0:p.toString)==null?void 0:g.call(p))})),R!==-1&&(y.docsByLocalValue.has(_)||y.docsByLocalValue.set(_,[]),y.docsByLocalValue.get(_).push(R))}})}}return yield Promise.all(Array.from(u.entries()).map(i=>l(null,[i],function*([a,f]){const S=s.models[a];if(!S)return;const h=new Set;if(f.localValueSets.forEach(_=>{_.forEach(R=>h.add(R))}),h.size===0)return;const y=[...new Set(f.virtuals.map(_=>_.options.foreignField))],N=Array.from(h);let T;y.length===1?T={[String(y[0])]:{$in:N}}:T={$or:y.map(_=>({[_]:{$in:N}}))};const x=yield S.find(T,n).lean();for(const _ of f.virtuals){const{name:R,options:v}=_,b=x.filter(E=>{const m=E[v.foreignField];return m!=null&&h.has(String(m))});if(v.count){const E=new Map;b.forEach(m=>{var p;const g=(p=m[v.foreignField])==null?void 0:p.toString();g&&E.set(g,(E.get(g)||0)+1)}),f.localValueSets.get(R).forEach(m=>{const p=f.docsByLocalValue.get(m)||[],g=E.get(m)||0;p.forEach(w=>{const C=o[w];C[R]===void 0&&(C[R]=g)})})}else{const E=new Map;b.forEach(m=>{var p;const g=(p=m[v.foreignField])==null?void 0:p.toString();g&&(E.has(g)||E.set(g,[]),E.get(g).push(m))}),f.localValueSets.get(R).forEach(m=>{const p=f.docsByLocalValue.get(m)||[],g=E.get(m)||[],w=v.justOne?g[0]||null:g;p.forEach(C=>{const L=o[C];L[R]=w})})}}}))),o})}class oe{constructor(t,e){re(this,"collection"),this.collection=t.collection(e)}createOne(t){return l(this,null,function*(){try{const e=O(O({},M.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 d.catchError(e)}})}createMany(t){return l(this,null,function*(){try{const e=t.map(n=>O(O({},M.createGenericFields()),n)),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 d.catchError(e)}})}findOne(t){return l(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 d.catchError(e)}})}findAll(){return l(this,arguments,function*(t={}){try{return{success:!0,message:"Documents retrieved successfully",result:yield this.collection.find(t).toArray()}}catch(e){return d.catchError(e)}})}count(){return l(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 d.catchError(e)}})}updateOne(t,e){return l(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 d.catchError(r)}})}updateMany(t,e){return l(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 d.catchError(r)}})}deleteOne(t){return l(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 d.catchError(e)}})}deleteMany(t){return l(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 d.catchError(e)}})}}class ue{constructor(t){this.model=t}getModelName(){return this.model.modelName}getDynamicVirtuals(){return this.model.schema.statics._dynamicVirtuals}populateDynamicVirtualsForDocument(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();if(r&&r.length>0){const n=yield z(this.model.base,[t],r,e);return n&&n[0]?n[0]:t}return t})}populateDynamicVirtualsForDocuments(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();return r&&r.length>0&&t.length>0?yield z(this.model.base,t,r,e):t})}findOne(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=V.normalizeMongoFilter(t),o=this.model.findOne(c,e,r),u=this.getDynamicVirtuals(),i=I(n,u);i&&o.populate(i);const a=yield o.exec();return a?{success:!0,result:yield this.populateDynamicVirtualsForDocument(a,n)}:{success:!1,message:`No ${this.getModelName()} found.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(c){return d.catchError(c)}})}findAll(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=V.normalizeMongoFilter(t),o=this.model.find(c,e,r),u=this.getDynamicVirtuals(),i=I(n,u);i&&o.populate(i);const a=yield o.exec();return{success:!0,result:yield this.populateDynamicVirtualsForDocuments(a,n)}}catch(c){return d.catchError(c)}})}findPaging(){return l(this,arguments,function*(t={},e={}){try{const r=V.normalizeMongoFilter(t),n=this.getDynamicVirtuals(),c=O({},e);e.populate&&(c.populate=I(e.populate,n));const o=yield this.model.paginate(r,c),u=yield this.populateDynamicVirtualsForDocuments(o.docs,e.populate);return{success:!0,result:P(O({},o),{docs:u})}}catch(r){return d.catchError(r)}})}findPagingAggregate(t){return l(this,arguments,function*(e,r={}){try{const n=this.getDynamicVirtuals(),c=O({},r);r.populate&&(c.populate=I(r.populate,n));const o=yield this.model.aggregatePaginate(this.model.aggregate(e),c),u=yield this.populateDynamicVirtualsForDocuments(o.docs,r.populate);return{success:!0,result:P(O({},o),{docs:u})}}catch(n){return d.catchError(n)}})}count(){return l(this,arguments,function*(t={}){try{const e=V.normalizeMongoFilter(t);return{success:!0,result:yield this.model.countDocuments(e)}}catch(e){return d.catchError(e)}})}createOne(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.create(t)}}catch(e){return d.catchError(e)}})}createMany(t){return l(this,arguments,function*(e,r={}){try{return{success:!0,result:(yield this.model.insertMany(e,r)).map(o=>o instanceof K.Document?o.toObject():null).filter(o=>o!==null)}}catch(n){return d.catchError(n)}})}updateOne(){return l(this,arguments,function*(t={},e={},r={}){try{const n=V.normalizeMongoFilter(t),c=yield this.model.findOneAndUpdate(n,e,O({new:!0},r)).exec();return c?{success:!0,result:c}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(n){return d.catchError(n)}})}updateMany(){return l(this,arguments,function*(t={},e={},r={}){try{const n=V.normalizeMongoFilter(t);return{success:!0,result:yield this.model.updateMany(n,e,r).exec()}}catch(n){return d.catchError(n)}})}deleteOne(){return l(this,arguments,function*(t={},e={}){try{const r=V.normalizeMongoFilter(t),n=yield this.model.findOneAndDelete(r,e).exec();return n?{success:!0,result:n}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return d.catchError(r)}})}deleteMany(){return l(this,arguments,function*(t={},e={}){try{const r=V.normalizeMongoFilter(t),n=yield this.model.deleteMany(r,e).exec();return n.deletedCount===0?{success:!1,message:"No documents found to delete.",code:D.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:n}}catch(r){return d.catchError(r)}})}createShortId(t,e=4){return l(this,null,function*(){try{const n=Array.from({length:10},(u,i)=>j.generateShortId(t,i+e)),o=(yield Promise.all(n.map(u=>this.model.exists({shortId:u})))).findIndex(u=>!u);if(o!==-1){const u=n[o];if(u)return{success:!0,result:u}}return{success:!1,message:"Failed to create a unique shortId",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return d.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,haveHistory:n=!1,filter:c}){const o=O({},c!=null?c:{});return r?P(O({},o),{$or:[{[`slug.${e}`]:t},...n?[{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]:[]]}):P(O({},o),{$or:[{slug:t},...n?[{slugHistory:t}]:[]]})}createUniqueSlug(t){return l(this,arguments,function*({slug:e,field:r,isObject:n,haveHistory:c,filter:o}){if(!e||typeof e!="string")throw new Error("Invalid slug provided: must be a non-empty string");const u=j.generateSlug(e);if(!(yield this.model.exists(this.createSlugQuery({slug:u,field:r,isObject:n,haveHistory:c,filter:o}))))return u;for(let S=1;S<=H.MONGO_SLUG_MAX_ATTEMPTS;S++){const h=`${u}-${S}`;if(!(yield this.model.exists(this.createSlugQuery({slug:h,field:r,isObject:n,haveHistory:c,filter:o}))))return h}const a=Date.now(),f=Math.random().toString(36).substring(2,8);return`${u}-${a}-${f}`})}createSlug(t){return l(this,arguments,function*({field:e,from:r,filter:n,haveHistory:c}){try{const o=r[e];return q.isObject(o)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(o).map(f=>l(this,[f],function*([S,h]){const y=yield this.createUniqueSlug({slug:h,field:S,isObject:!0,haveHistory:c,filter:n});return[S,y]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:o,field:e,isObject:!1,haveHistory:c,filter:n})}}catch(o){return d.catchError(o)}})}checkSlug(t){return l(this,arguments,function*({slug:e,field:r,from:n,filter:c,haveHistory:o}){try{const u=n[r];if(q.isObject(u)){const h=Object.values(u).map(N=>j.generateSlug(N));return(yield Promise.all(h.map(N=>this.model.exists(this.createSlugQuery({slug:N,field:r,isObject:!0,haveHistory:o,filter:c}))))).some(N=>N)?{success:!0,result:!0}:{success:!0,result:!1}}const a=j.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:a,field:r,isObject:!1,filter:c})))!==null}}catch(u){return d.catchError(u)}})}aggregate(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return d.catchError(e)}})}distinct(t){return l(this,arguments,function*(e,r={},n={}){try{return{success:!0,result:yield this.model.distinct(e,r,n)}}catch(c){return d.catchError(c)}})}}exports.MongoController=oe;exports.MongooseController=ue;exports.mongo=M;
|
|
@@ -415,7 +415,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
415
415
|
* @param options.filter - Additional filter conditions to apply to the query.
|
|
416
416
|
* @returns A MongoDB query object for checking slug existence.
|
|
417
417
|
*/
|
|
418
|
-
createSlugQuery({ slug, field, isObject, filter }: I_Input_GenerateSlug<T>): {
|
|
418
|
+
createSlugQuery({ slug, field, isObject, haveHistory, filter }: I_Input_GenerateSlug<T>): {
|
|
419
419
|
$or: ({
|
|
420
420
|
[x: string]: string;
|
|
421
421
|
slugHistory?: undefined;
|
|
@@ -582,7 +582,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
582
582
|
* @param options.filter - Additional filter conditions to apply when checking slug existence.
|
|
583
583
|
* @returns A promise that resolves to a unique slug string.
|
|
584
584
|
*/
|
|
585
|
-
createUniqueSlug({ slug, field, isObject, filter }: I_Input_GenerateSlug<T>): Promise<string>;
|
|
585
|
+
createUniqueSlug({ slug, field, isObject, haveHistory, filter }: I_Input_GenerateSlug<T>): Promise<string>;
|
|
586
586
|
/**
|
|
587
587
|
* Creates a slug for a document field.
|
|
588
588
|
* This method handles both simple string fields and object fields with nested slug generation.
|
|
@@ -593,7 +593,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
593
593
|
* @param options.filter - Additional filter conditions to apply when checking slug existence.
|
|
594
594
|
* @returns A promise that resolves to a standardized response with the created slug(s).
|
|
595
595
|
*/
|
|
596
|
-
createSlug<R = string>({ field, from, filter }: I_Input_CreateSlug<T>): Promise<I_Return<R>>;
|
|
596
|
+
createSlug<R = string>({ field, from, filter, haveHistory }: I_Input_CreateSlug<T>): Promise<I_Return<R>>;
|
|
597
597
|
/**
|
|
598
598
|
* Checks if a slug already exists in the collection.
|
|
599
599
|
* This method verifies slug existence in both current and historical slug fields.
|
|
@@ -605,7 +605,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
605
605
|
* @param options.filter - Additional filter conditions to apply to the query.
|
|
606
606
|
* @returns A promise that resolves to a standardized response indicating whether the slug exists.
|
|
607
607
|
*/
|
|
608
|
-
checkSlug({ slug, field, from, filter }: I_Input_CheckSlug<T>): Promise<I_Return<boolean>>;
|
|
608
|
+
checkSlug({ slug, field, from, filter, haveHistory }: I_Input_CheckSlug<T>): Promise<I_Return<boolean>>;
|
|
609
609
|
/**
|
|
610
610
|
* Performs aggregation operations on the collection.
|
|
611
611
|
*
|
|
@@ -613,4 +613,13 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
613
613
|
* @returns A promise that resolves to a standardized response with the aggregation results.
|
|
614
614
|
*/
|
|
615
615
|
aggregate(pipeline: T_PipelineStage[]): Promise<I_Return<T[]>>;
|
|
616
|
+
/**
|
|
617
|
+
* Retrieves distinct values for the specified key from the collection.
|
|
618
|
+
*
|
|
619
|
+
* @param key - The field for which to return distinct values.
|
|
620
|
+
* @param filter - The filter query to apply (optional).
|
|
621
|
+
* @param options - Additional options for the distinct operation (optional).
|
|
622
|
+
* @returns A promise that resolves to a standardized response with the array of distinct values.
|
|
623
|
+
*/
|
|
624
|
+
distinct(key: string, filter?: T_FilterQuery<T>, options?: T_QueryOptions<T>): Promise<I_Return<unknown[]>>;
|
|
616
625
|
}
|