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