@cyberskill/shared 2.10.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 q=require("lodash-es"),B=require("migrate-mongo"),K=require("mongoose
|
|
2
|
-
module.exports = ${JSON.stringify(
|
|
3
|
-
${
|
|
4
|
-
`;F.pathExistsSync(
|
|
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;
|
|
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;
|
|
@@ -412,6 +412,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
412
412
|
* @param options.slug - The slug string to check for existence.
|
|
413
413
|
* @param options.field - The field name for object-based slug checking.
|
|
414
414
|
* @param options.isObject - Whether the slug is stored as an object with nested fields.
|
|
415
|
+
* @param options.haveHistory - Whether to check historical slug fields for existence.
|
|
415
416
|
* @param options.filter - Additional filter conditions to apply to the query.
|
|
416
417
|
* @returns A MongoDB query object for checking slug existence.
|
|
417
418
|
*/
|
|
@@ -579,6 +580,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
579
580
|
* @param options.slug - The base slug string to make unique.
|
|
580
581
|
* @param options.field - The field name for object-based slug checking.
|
|
581
582
|
* @param options.isObject - Whether the slug is stored as an object with nested fields.
|
|
583
|
+
* @param options.haveHistory - Whether to check historical slug fields for uniqueness.
|
|
582
584
|
* @param options.filter - Additional filter conditions to apply when checking slug existence.
|
|
583
585
|
* @returns A promise that resolves to a unique slug string.
|
|
584
586
|
*/
|
|
@@ -590,6 +592,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
590
592
|
* @param options - Configuration for slug creation including field, source document, and filter.
|
|
591
593
|
* @param options.field - The field name to create a slug for.
|
|
592
594
|
* @param options.from - The source document containing the field value.
|
|
595
|
+
* @param options.haveHistory - Whether to check historical slug fields for uniqueness.
|
|
593
596
|
* @param options.filter - Additional filter conditions to apply when checking slug existence.
|
|
594
597
|
* @returns A promise that resolves to a standardized response with the created slug(s).
|
|
595
598
|
*/
|
|
@@ -602,6 +605,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
|
|
|
602
605
|
* @param options.slug - The slug string to check for existence.
|
|
603
606
|
* @param options.field - The field name for object-based slug checking.
|
|
604
607
|
* @param options.from - The source document containing the field value.
|
|
608
|
+
* @param options.haveHistory - Whether to check historical slug fields for existence.
|
|
605
609
|
* @param options.filter - Additional filter conditions to apply to the query.
|
|
606
610
|
* @returns A promise that resolves to a standardized response indicating whether the slug exists.
|
|
607
611
|
*/
|