@cyberskill/shared 2.11.0 → 2.12.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.
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
module.exports = ${JSON.stringify(
|
|
3
|
-
${
|
|
4
|
-
`;
|
|
5
|
-
`).includes(A.MIGRATE_MONGO_CONFIG)||P.appendFileSync(A.PATH.GIT_IGNORE,e):P.writeFileSync(A.PATH.GIT_IGNORE,e)}}),regexify(s,t){if(!s)return{};let e=$.cloneDeep(s);if(!t||t.length===0)return e;for(const r of t){const n=r.toString().split("."),c=b.getNestedValue(e,n);if(typeof c=="string"&&c.length>0){const o={$regex:`.*${k.regexSearchMapper(c)}.*`,$options:"i"};e=b.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 q(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 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 L(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=$.cloneDeep(t);o.forEach(i=>{c.forEach(({name:a,options:f})=>{a in i||(i[a]=f.count?0:f.justOne?null:[])})});const u=new Map;for(const i of c){const{name:a,options:f}=i,m=se(o,a,f);for(const h of m){u.has(h.model)||u.set(h.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const E=u.get(h.model);E.virtuals.find(V=>V.name===a)||(E.virtuals.push(i),E.localValueSets.set(a,new Set));const N=E.localValueSets.get(a);h.docs.forEach(V=>{const C=V[f.localField];if(C!=null){const _=String(C);N.add(_);let D=-1;const v=V;v.id!==void 0?D=o.findIndex(F=>F.id===v.id):v._id!==void 0&&(D=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))})),D!==-1&&(E.docsByLocalValue.has(_)||E.docsByLocalValue.set(_,[]),E.docsByLocalValue.get(_).push(D))}})}}return yield Promise.all(Array.from(u.entries()).map(i=>l(null,[i],function*([a,f]){const m=s.models[a];if(!m)return;const h=new Set;if(f.localValueSets.forEach(_=>{_.forEach(D=>h.add(D))}),h.size===0)return;const E=[...new Set(f.virtuals.map(_=>_.options.foreignField))],N=Array.from(h);let V;E.length===1?V={[String(E[0])]:{$in:N}}:V={$or:E.map(_=>({[_]:{$in:N}}))};const C=yield m.find(V,n).lean();for(const _ of f.virtuals){const{name:D,options:v}=_,F=C.filter(S=>{const g=S[v.foreignField];return g!=null&&h.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)}),f.localValueSets.get(D).forEach(g=>{const p=f.docsByLocalValue.get(g)||[],y=S.get(g)||0;p.forEach(w=>{const j=o[w];j[D]===void 0&&(j[D]=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))}),f.localValueSets.get(D).forEach(g=>{const p=f.docsByLocalValue.get(g)||[],y=S.get(g)||[],w=v.justOne?y[0]||null:y;p.forEach(j=>{const B=o[j];B[D]=w})})}}}))),o})}class ce{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:R.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:R.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:R.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:R.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:R.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:R.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:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents deleted successfully",result:e}}catch(e){return d.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 L(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 L(this.model.base,t,r,e):t})}findOne(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=b.normalizeMongoFilter(t),o=this.model.findOne(c,e,r),u=this.getDynamicVirtuals(),i=q(n,u);i&&o.populate(i);const a=yield o.exec().then(m=>m instanceof T.C_Document?m.toObject():m);return a?{success:!0,result:yield this.populateDynamicVirtualsForDocument(a,n)}:{success:!1,message:`No ${this.getModelName()} found.`,code:R.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(c){return d.catchError(c)}})}findAll(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=b.normalizeMongoFilter(t),o=this.model.find(c,e,r),u=this.getDynamicVirtuals(),i=q(n,u);i&&o.populate(i);const a=yield o.exec().then(m=>m==null?void 0:m.map(h=>h instanceof T.C_Document?h.toObject():h));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=b.normalizeMongoFilter(t),n=this.getDynamicVirtuals(),c=O({},e);e.populate&&(c.populate=q(e.populate,n));const o=yield this.model.paginate(r,c),u=yield this.populateDynamicVirtualsForDocuments(o.docs.map(i=>i instanceof T.C_Document?i.toObject():i),e.populate);return{success:!0,result:x(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=q(r.populate,n));const o=yield this.model.aggregatePaginate(this.model.aggregate(e),c),u=yield this.populateDynamicVirtualsForDocuments(o.docs.map(i=>i instanceof T.C_Document?i.toObject():i),r.populate);return{success:!0,result:x(O({},o),{docs:u})}}catch(n){return d.catchError(n)}})}count(){return l(this,arguments,function*(t={}){try{const e=b.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).then(r=>r instanceof T.C_Document?r.toObject():r)}}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).then(c=>c.map(o=>o instanceof T.C_Document?o.toObject():o))}}catch(n){return d.catchError(n)}})}updateOne(){return l(this,arguments,function*(t={},e={},r={}){try{const n=b.normalizeMongoFilter(t),c=yield this.model.findOneAndUpdate(n,e,O({new:!0},r)).exec().then(o=>o instanceof T.C_Document?o.toObject():o);return c?{success:!0,result:c}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:R.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(n){return d.catchError(n)}})}updateMany(){return l(this,arguments,function*(t={},e={},r={}){try{const n=b.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=b.normalizeMongoFilter(t),n=yield this.model.findOneAndDelete(r,e).exec().then(c=>c instanceof T.C_Document?c.toObject():c);return n?{success:!0,result:n}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:R.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return d.catchError(r)}})}deleteMany(){return l(this,arguments,function*(t={},e={}){try{const r=b.normalizeMongoFilter(t),n=yield this.model.deleteMany(r,e).exec();return n.deletedCount===0?{success:!1,message:"No documents found to delete.",code:R.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)=>I.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:R.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?x(O({},o),{$or:[{[`slug.${e}`]:t},...n?[{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]:[]]}):x(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=I.generateSlug(e);if(!(yield this.model.exists(this.createSlugQuery({slug:u,field:r,isObject:n,haveHistory:c,filter:o}))))return u;for(let m=1;m<=H.MONGO_SLUG_MAX_ATTEMPTS;m++){const h=`${u}-${m}`;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 $.isObject(o)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(o).map(f=>l(this,[f],function*([m,h]){const E=yield this.createUniqueSlug({slug:h,field:m,isObject:!0,haveHistory:c,filter:n});return[m,E]}))))}:{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($.isObject(u)){const h=Object.values(u).map(N=>I.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=I.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=ce;exports.MongooseController=oe;exports.mongo=M;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("lodash-es"),B=require("migrate-mongo"),K=require("mongoose-aggregate-paginate-v2"),Q=require("mongoose-paginate-v2"),U=require("uuid"),W=require("./mongo.constant.cjs"),b=require("../../util/object/object.util.cjs"),H=require("../../util/common/common.util.cjs"),F=require("../fs/fs.util.cjs"),M=require("../path/path.constant.cjs"),k=require("../../util/validate/validate.util.cjs"),C=require("../../util/string/string.util.cjs"),R=require("../../constant/response-status.cjs"),f=require("../log/log.util.cjs");var J=Object.defineProperty,X=Object.defineProperties,Y=Object.getOwnPropertyDescriptors,G=Object.getOwnPropertySymbols,Z=Object.prototype.hasOwnProperty,ee=Object.prototype.propertyIsEnumerable,$=(c,t,e)=>t in c?J(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e,O=(c,t)=>{for(var e in t||(t={}))Z.call(t,e)&&$(c,e,t[e]);if(G)for(var e of G(t))ee.call(t,e)&&$(c,e,t[e]);return c},P=(c,t)=>X(c,Y(t)),te=(c,t,e)=>$(c,typeof t!="symbol"?t+"":t,e),a=(c,t,e)=>new Promise((r,n)=>{var s=o=>{try{l(e.next(o))}catch(i){n(i)}},u=o=>{try{l(e.throw(o))}catch(i){n(i)}},l=o=>o.done?r(o.value):Promise.resolve(o.value).then(s,u);l((e=e.apply(c,t)).next())});function re(c){return c===c.toUpperCase()?c.charAt(0).toUpperCase()+c.slice(1).toLowerCase():c}const T={createGenericFields(){return{id:U.v4(),isDel:!1,createdAt:new Date,updatedAt:new Date}},applyPlugins(c,t){t.filter(e=>typeof e=="function").forEach(e=>c.plugin(e))},applyMiddlewares(c,t){t.forEach(({method:e,pre:r,post:n})=>{e&&r&&c.pre(e,r),e&&n&&c.post(e,n)})},createGenericSchema(c){return new c.Schema({id:{type:String,default:U.v4,unique:!0},isDel:{type:Boolean,default:!1}},{timestamps:!0})},createSchema({mongoose:c,schema:t,virtuals:e=[],standalone:r=!1}){const n=new c.Schema(t,{toJSON:{virtuals:!0},toObject:{virtuals:!0}});return e.forEach(({name:s,options:u,get:l})=>{if(T.isDynamicVirtual(u)){const o=n.statics;o._dynamicVirtuals||(o._dynamicVirtuals=[]),o._dynamicVirtuals.push({name:s,options:u});const i=n.virtual(s);l?i.get(l):i.get(function(){var d;return((d=this._populated)==null?void 0:d[s])||(u!=null&&u.count?0:u!=null&&u.justOne?null:[])})}else{const o=n.virtual(s,u);l&&o.get(l)}}),r||n.add(T.createGenericSchema(c)),n},createModel({mongoose:c,name:t,schema:e,virtuals:r=[],pagination:n=!0,aggregate:s=!0,middlewares:u=[]}){if(!t)throw new Error("Model name is required.");if(c.models[t])return c.models[t];const l=T.createSchema({mongoose:c,schema:e,virtuals:r});return(n||s)&&T.applyPlugins(l,[n&&Q,s&&K]),T.applyMiddlewares(l,u),c.model(t,l)},validator:{isRequired(){return function(c){return a(this,null,function*(){return!k.validate.isEmpty(c)})}},isUnique(c){return function(t){return a(this,null,function*(){if(!Array.isArray(c)||c.length===0)throw new Error("Fields must be a non-empty array of strings.");const e={$or:c.map(n=>({[n]:t}))};return!(yield this.constructor.exists(e))})}},matchesRegex(c){return function(t){return a(this,null,function*(){if(!Array.isArray(c)||c.some(e=>!(e instanceof RegExp)))throw new Error("regexArray must be an array of valid RegExp objects.");return c.every(e=>e.test(t))})}}},migrate:P(O({},B),{setConfig:c=>{const t=`// This file is automatically generated by the Cyberskill CLI.
|
|
2
|
+
module.exports = ${JSON.stringify(c,null,4)}`;F.writeFileSync(M.PATH.MIGRATE_MONGO_CONFIG,t);const e=`
|
|
3
|
+
${M.MIGRATE_MONGO_CONFIG}
|
|
4
|
+
`;F.pathExistsSync(M.PATH.GIT_IGNORE)?F.readFileSync(M.PATH.GIT_IGNORE,"utf-8").split(`
|
|
5
|
+
`).includes(M.MIGRATE_MONGO_CONFIG)||F.appendFileSync(M.PATH.GIT_IGNORE,e):F.writeFileSync(M.PATH.GIT_IGNORE,e)}}),regexify(c,t){if(!c)return{};let e=q.cloneDeep(c);if(!t||t.length===0)return e;for(const r of t){const n=r.toString().split("."),s=b.getNestedValue(e,n);if(typeof s=="string"&&s.length>0){const u={$regex:`.*${H.regexSearchMapper(s)}.*`,$options:"i"};e=b.setNestedValue(e,n,u)}}return e},isDynamicVirtual(c){return!!(c&&typeof c.ref=="function")},getNewRecords(c,t,e){return a(this,null,function*(){const r=yield c.findAll({});return r.success?t.filter(s=>!r.result.some(u=>e(u,s))):t})},getExistingRecords(c,t,e){return a(this,null,function*(){const r=yield c.findAll({});return r.success?r.result.filter(s=>t.some(u=>e(s,u))):[]})}};function I(c,t){if(!c||!t||t.length===0)return c;const e=new Set(t.map(r=>r.name));if(Array.isArray(c)){const r=c.filter(n=>{if(typeof n=="string")return!e.has(n);if(typeof n=="object"&&n!==null){const s=n;return!e.has(s.path||s.populate||"")}return!0});return r.length>0?r:void 0}if(typeof c=="string")return e.has(c)?void 0:c;if(typeof c=="object"&&c!==null){const r=c,n=r.path||r.populate||"";return e.has(n)?void 0:c}return c}function ne(c,t,e){if(!c.length||!t||!(e!=null&&e.ref))return[];const r=new Map;return c.forEach(n=>{try{const s=e.ref(n);if(s==null)return;const u=typeof s=="string"?s:String(s);if(u&&u.trim()!==""){const l=re(u);r.has(l)||r.set(l,[]),r.get(l).push(n)}}catch(s){f.catchError(new Error(`Dynamic ref function failed for virtual "${t}": ${s instanceof Error?s.message:String(s)}`))}}),Array.from(r.entries()).map(([n,s])=>({model:n,docs:s}))}function z(c,t,e,r,n){return a(this,null,function*(){if(!t.length||!e.length||!r)return t;const s=e.filter(o=>{if(Array.isArray(r))return r.length>0&&r.some(i=>typeof i=="string"?i===o.name:i.path===o.name);if(typeof r=="string")return r===o.name;if(typeof r=="object"&&r!==null){const i=r;return i.path&&i.path===o.name||i.populate&&i.populate===o.name}return!1});if(s.length===0)return t;const u=q.cloneDeep(t);u.forEach(o=>{s.forEach(({name:i,options:d})=>{i in o||(o[i]=d.count?0:d.justOne?null:[])})});const l=new Map;for(const o of s){const{name:i,options:d}=o,m=ne(u,i,d);for(const h of m){l.has(h.model)||l.set(h.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const g=l.get(h.model);g.virtuals.find(V=>V.name===i)||(g.virtuals.push(o),g.localValueSets.set(i,new Set));const D=g.localValueSets.get(i);h.docs.forEach(V=>{const x=V[d.localField];if(x!=null){const _=String(x);D.add(_);let v=-1;const N=V;N.id!==void 0?v=u.findIndex(A=>A.id===N.id):N._id!==void 0&&(v=u.findIndex(A=>{var S,y,p,E;return((y=(S=A._id)==null?void 0:S.toString)==null?void 0:y.call(S))===((E=(p=N._id)==null?void 0:p.toString)==null?void 0:E.call(p))})),v!==-1&&(g.docsByLocalValue.has(_)||g.docsByLocalValue.set(_,[]),g.docsByLocalValue.get(_).push(v))}})}}return yield Promise.all(Array.from(l.entries()).map(o=>a(null,[o],function*([i,d]){const m=c.models[i];if(!m)return;const h=new Set;if(d.localValueSets.forEach(_=>{_.forEach(v=>h.add(v))}),h.size===0)return;const g=[...new Set(d.virtuals.map(_=>_.options.foreignField))],D=Array.from(h);let V;g.length===1?V={[String(g[0])]:{$in:D}}:V={$or:g.map(_=>({[_]:{$in:D}}))};const x=yield m.find(V,n).lean();for(const _ of d.virtuals){const{name:v,options:N}=_,A=x.filter(S=>{const y=S[N.foreignField];return y!=null&&h.has(String(y))});if(N.count){const S=new Map;A.forEach(y=>{var p;const E=(p=y[N.foreignField])==null?void 0:p.toString();E&&S.set(E,(S.get(E)||0)+1)}),d.localValueSets.get(v).forEach(y=>{const p=d.docsByLocalValue.get(y)||[],E=S.get(y)||0;p.forEach(w=>{const j=u[w];j[v]===void 0&&(j[v]=E)})})}else{const S=new Map;A.forEach(y=>{var p;const E=(p=y[N.foreignField])==null?void 0:p.toString();E&&(S.has(E)||S.set(E,[]),S.get(E).push(y))}),d.localValueSets.get(v).forEach(y=>{const p=d.docsByLocalValue.get(y)||[],E=S.get(y)||[],w=N.justOne?E[0]||null:E;p.forEach(j=>{const L=u[j];L[v]=w})})}}}))),u})}class se{constructor(t,e){te(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:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(e){return f.catchError(e)}})}createMany(t){return a(this,null,function*(){try{const e=t.map(n=>O(O({},T.createGenericFields()),n)),r=yield this.collection.insertMany(e);return r.insertedCount===0?{success:!1,message:"No documents were inserted",code:R.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:R.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:R.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:R.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:R.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:R.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}getDynamicVirtuals(){return this.model.schema.statics._dynamicVirtuals}populateDynamicVirtualsForDocument(t,e){return a(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 a(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 a(this,arguments,function*(t={},e={},r={},n){var s,u;try{const l=b.normalizeMongoFilter(t),o=this.model.findOne(l,e,r),i=this.getDynamicVirtuals(),d=I(n,i);d&&o.populate(d);const m=yield o.exec();if(!m)return{success:!1,message:`No ${this.getModelName()} found.`,code:R.RESPONSE_STATUS.NOT_FOUND.CODE};const h=yield this.populateDynamicVirtualsForDocument(m,n);return{success:!0,result:(u=(s=h==null?void 0:h.toObject)==null?void 0:s.call(h))!=null?u:h}}catch(l){return f.catchError(l)}})}findAll(){return a(this,arguments,function*(t={},e={},r={},n){try{const s=b.normalizeMongoFilter(t),u=this.model.find(s,e,r),l=this.getDynamicVirtuals(),o=I(n,l);o&&u.populate(o);const i=yield u.exec();return{success:!0,result:(yield this.populateDynamicVirtualsForDocuments(i,n)).map(m=>{var h,g;return(g=(h=m==null?void 0:m.toObject)==null?void 0:h.call(m))!=null?g:m})}}catch(s){return f.catchError(s)}})}findPaging(){return a(this,arguments,function*(t={},e={}){try{const r=b.normalizeMongoFilter(t),n=this.getDynamicVirtuals(),s=O({},e);e.populate&&(s.populate=I(e.populate,n));const u=yield this.model.paginate(r,s),l=yield this.populateDynamicVirtualsForDocuments(u.docs,e.populate);return{success:!0,result:P(O({},u),{docs:l.map(o=>{var i,d;return(d=(i=o==null?void 0:o.toObject)==null?void 0:i.call(o))!=null?d:o})})}}catch(r){return f.catchError(r)}})}findPagingAggregate(t){return a(this,arguments,function*(e,r={}){try{const n=this.getDynamicVirtuals(),s=O({},r);r.populate&&(s.populate=I(r.populate,n));const u=yield this.model.aggregatePaginate(this.model.aggregate(e),s),l=yield this.populateDynamicVirtualsForDocuments(u.docs,r.populate);return{success:!0,result:P(O({},u),{docs:l.map(o=>{var i,d;return(d=(i=o==null?void 0:o.toObject)==null?void 0:i.call(o))!=null?d:o})})}}catch(n){return f.catchError(n)}})}count(){return a(this,arguments,function*(t={}){try{const e=b.normalizeMongoFilter(t);return{success:!0,result:yield this.model.countDocuments(e)}}catch(e){return f.catchError(e)}})}createOne(t){return a(this,null,function*(){var e,r;try{const n=yield this.model.create(t);return{success:!0,result:(r=(e=n==null?void 0:n.toObject)==null?void 0:e.call(n))!=null?r:n}}catch(n){return f.catchError(n)}})}createMany(t){return a(this,arguments,function*(e,r={}){try{return{success:!0,result:(yield this.model.insertMany(e,r)).map(s=>{var u,l;return(l=(u=s==null?void 0:s.toObject)==null?void 0:u.call(s))!=null?l:s})}}catch(n){return f.catchError(n)}})}updateOne(){return a(this,arguments,function*(t={},e={},r={}){var n,s;try{const u=b.normalizeMongoFilter(t),l=yield this.model.findOneAndUpdate(u,e,O({new:!0},r)).exec();return l?{success:!0,result:(s=(n=l==null?void 0:l.toObject)==null?void 0:n.call(l))!=null?s:l}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:R.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(u){return f.catchError(u)}})}updateMany(){return a(this,arguments,function*(t={},e={},r={}){try{const n=b.normalizeMongoFilter(t);return{success:!0,result:yield this.model.updateMany(n,e,r).exec()}}catch(n){return f.catchError(n)}})}deleteOne(){return a(this,arguments,function*(t={},e={}){var r,n;try{const s=b.normalizeMongoFilter(t),u=yield this.model.findOneAndDelete(s,e).exec();return u?{success:!0,result:(n=(r=u==null?void 0:u.toObject)==null?void 0:r.call(u))!=null?n:u}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:R.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(s){return f.catchError(s)}})}deleteMany(){return a(this,arguments,function*(t={},e={}){try{const r=b.normalizeMongoFilter(t),n=yield this.model.deleteMany(r,e).exec();return n.deletedCount===0?{success:!1,message:"No documents found to delete.",code:R.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:n}}catch(r){return f.catchError(r)}})}createShortId(t,e=4){return a(this,null,function*(){try{const n=Array.from({length:10},(l,o)=>C.generateShortId(t,o+e)),u=(yield Promise.all(n.map(l=>this.model.exists({shortId:l})))).findIndex(l=>!l);if(u!==-1){const l=n[u];if(l)return{success:!0,result:l}}return{success:!1,message:"Failed to create a unique shortId",code:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return f.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,haveHistory:n=!1,filter:s}){const u=O({},s!=null?s:{});return r?P(O({},u),{$or:[{[`slug.${e}`]:t},...n?[{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]:[]]}):P(O({},u),{$or:[{slug:t},...n?[{slugHistory:t}]:[]]})}createUniqueSlug(t){return a(this,arguments,function*({slug:e,field:r,isObject:n,haveHistory:s,filter:u}){if(!e||typeof e!="string")throw new Error("Invalid slug provided: must be a non-empty string");const l=C.generateSlug(e);if(!(yield this.model.exists(this.createSlugQuery({slug:l,field:r,isObject:n,haveHistory:s,filter:u}))))return l;for(let m=1;m<=W.MONGO_SLUG_MAX_ATTEMPTS;m++){const h=`${l}-${m}`;if(!(yield this.model.exists(this.createSlugQuery({slug:h,field:r,isObject:n,haveHistory:s,filter:u}))))return h}const i=Date.now(),d=Math.random().toString(36).substring(2,8);return`${l}-${i}-${d}`})}createSlug(t){return a(this,arguments,function*({field:e,from:r,filter:n,haveHistory:s}){try{const u=r[e];return q.isObject(u)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(u).map(d=>a(this,[d],function*([m,h]){const g=yield this.createUniqueSlug({slug:h,field:m,isObject:!0,haveHistory:s,filter:n});return[m,g]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:u,field:e,isObject:!1,haveHistory:s,filter:n})}}catch(u){return f.catchError(u)}})}checkSlug(t){return a(this,arguments,function*({slug:e,field:r,from:n,filter:s,haveHistory:u}){try{const l=n[r];if(q.isObject(l)){const h=Object.values(l).map(D=>C.generateSlug(D));return(yield Promise.all(h.map(D=>this.model.exists(this.createSlugQuery({slug:D,field:r,isObject:!0,haveHistory:u,filter:s}))))).some(D=>D)?{success:!0,result:!0}:{success:!0,result:!1}}const i=C.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:i,field:r,isObject:!1,filter:s})))!==null}}catch(l){return f.catchError(l)}})}aggregate(t){return a(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return f.catchError(e)}})}distinct(t){return a(this,arguments,function*(e,r={},n={}){try{return{success:!0,result:yield this.model.distinct(e,r,n)}}catch(s){return f.catchError(s)}})}}exports.MongoController=se;exports.MongooseController=ce;exports.mongo=T;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { default as mongooseRaw } from 'mongoose';
|
|
2
2
|
import { default as migrate } from 'migrate-mongo';
|
|
3
3
|
import { I_Return } from '../../typescript/index.js';
|
|
4
|
-
import { C_Db, 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
|
|
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
5
|
/**
|
|
6
6
|
* MongoDB utility object providing comprehensive database operations and utilities.
|
|
7
7
|
* This object contains methods for creating generic fields, applying plugins and middlewares,
|