@decaf-ts/db-decorators
Version:
Agnostic database decorators and repository
3 lines (2 loc) • 25.7 kB
JavaScript
import{Decoration as e,Metadata as t,propMetadata as r,apply as n,metadata as s}from"@decaf-ts/decoration";import{ModelKeys as o,validator as a,Validator as i,isEqual as c,DEFAULT_ERROR_MESSAGES as l,Validation as u,Hashing as d,type as f,Model as p,innerValidationDecorator as h,date as E,required as g,ValidationKeys as y,getChildNestedPropsToIgnore as m,ModelErrorDefinition as A,toConditionalPromise as T,validate as w}from"@decaf-ts/decorator-validation";import{__decorate as O,__metadata as P}from"tslib";import{ObjectAccumulator as v}from"typed-object-accumulator";import{Logging as R}from"@decaf-ts/logging";const D={REFLECT:o.MODEL+".persistence.",REPOSITORY:"repository",CLASS:"_class",ID:"id",INDEX:"index",UNIQUE:"unique",SERIALIZE:"serialize",READONLY:"readonly",TIMESTAMP:"timestamp",TRANSIENT:"transient",HASH:"hash",COMPOSED:"composed",GENERATED:"generated",VERSION:"version",ORIGINAL:"__originalObj"},b="_",S="dd/MM/yyyy HH:mm:ss:S",L={ID:{INVALID:"This Id is invalid",REQUIRED:"The Id is mandatory"},READONLY:{INVALID:"This cannot be updated"},TIMESTAMP:{REQUIRED:"Timestamp is Mandatory",DATE:"The Timestamp must the a valid date",INVALID:"This value must always increase"}},N={REFLECT:"db.update.validation.",TIMESTAMP:D.TIMESTAMP,READONLY:D.READONLY};let I=class extends i{constructor(){super(L.READONLY.INVALID)}hasErrors(e,...t){}updateHasErrors(e,t,r){if(void 0!==e)return c(e,t)?void 0:this.getMessage(r||this.message)}};I=O([a(N.READONLY),P("design:paramtypes",[])],I);let k=class extends i{constructor(){super(L.TIMESTAMP.INVALID)}hasErrors(e,...t){}updateHasErrors(e,t,r){if(void 0!==e){r=r||this.getMessage(r||this.message);try{e=new Date(e),t=new Date(t)}catch(e){return r}return e>t?void 0:r}}};k=O([a(N.TIMESTAMP),P("design:paramtypes",[])],k);class x extends i{constructor(e=l.DEFAULT,...t){super(e,...t)}}var C,M,j;u.updateKey=e=>N.REFLECT+e,(e=>{e.REFLECT="decaf.model.db.operations.",e.CREATE="create",e.READ="read",e.UPDATE="update",e.DELETE="delete",e.ON="on.",e.AFTER="after.",e.BLOCK="block"})(C||(C={})),(e=>{e.OPERATIONS="operations",e.RELATIONS="relations"})(M||(M={})),(e=>{e.CREATE_ALL="createAll",e.READ_ALL="readAll",e.UPDATE_ALL="updateAll",e.DELETE_ALL="deleteAll"})(j||(j={}));const U={CREATE:[C.CREATE],READ:[C.READ],UPDATE:[C.UPDATE],DELETE:[C.DELETE],CREATE_UPDATE:[C.CREATE,C.UPDATE],READ_CREATE:[C.READ,C.CREATE],ALL:[C.CREATE,C.READ,C.UPDATE,C.DELETE]};class F{constructor(){this.cache={}}get(e,t,r,n){n=n||[];const s=this.resolveOwner(e),o=this.resolveTargetName(e,s);if(o){const e=this.selectHandlers(o,t,r,s);e?.length&&n.unshift(...e)}else if("string"==typeof e||e===Object.prototype||Object.getPrototypeOf(e)===Object.prototype)return n;let a=Object.getPrototypeOf(e);return a?(a.constructor&&a.constructor.name===o&&(a=Object.getPrototypeOf(a)),a?this.get(a,t,r,n):n):n}register(e,t,r,n){const s=r.constructor.name,o=F.getHandlerName(e),a=this.resolveFlavour(r.constructor);this.cache[s]||(this.cache[s]={}),this.cache[s][n]||(this.cache[s][n]={}),this.cache[s][n][t]||(this.cache[s][n][t]={}),this.cache[s][n][t][a]||(this.cache[s][n][t][a]={}),this.cache[s][n][t][a][o]||(this.cache[s][n][t][a][o]=e)}resolveOwner(e){if(e&&"string"!=typeof e)return"function"==typeof e?e:e.constructor}resolveTargetName(e,t){return"string"==typeof e?e:t?.name}resolveFlavour(r){if(!r)return e.defaultFlavour;try{return t.flavourOf(r)}catch{return e.defaultFlavour}}selectHandlers(t,r,n,s){const o=this.cache[t]?.[r]?.[n];if(!o)return;const a=o[this.resolveFlavour(s)]||o[e.defaultFlavour]||this.firstBucket(o);if(!a)return;const i=Object.values(a);return i.length?i:void 0}firstBucket(e){for(const t of Object.values(e))if(t&&Object.keys(t).length)return t}static getHandlerName(e){return e.name?e.name:d.hash(e.toString())}}class H{constructor(){}static getHandlerName(e){return F.getHandlerName(e)}static key(e){return C.REFLECT+e}static get(e,t,r){return H.registry.get(e,t,r)}static getOpRegistry(){return H.registry||(H.registry=new F),H.registry}static register(e,t,r,n){H.getOpRegistry().register(e,t,r,n)}}class $ extends Error{constructor(e,t,r){if(t instanceof $)return t;super(`[${e}][${r}] ${t instanceof Error?t.message:t}`),this.code=r,t instanceof Error&&(this.stack=t.stack)}get message(){return`[${this.name}] ${this.code} | ${super.message.replaceAll(/\[.*?Error\]\[\d+\]\s/g,"")}`}toString(){return this.message}}class V extends ${constructor(e,t=V.name,r=999){super(t,e,r)}}class _ extends ${constructor(e,t=_.name,r=400){super(t,e,r)}}class z extends _{constructor(e){super(e,z.name,422)}}class G extends ${constructor(e,t=G.name,r=500){super(t,e,r)}}class Y extends G{constructor(e){super(e,Y.name,500)}}class K extends _{constructor(e){super(e,K.name,404)}}class B extends _{constructor(e){super(e,B.name,409)}}const Q={priority:50},J=(e,t,r,n)=>{const s=r.constructor.name;if(!s)throw new G("Could not determine model class");n=n||{},e.props.handlers[s]&&e.props.handlers[s][t]&&(n={...e.props.handlers[s][t],...n});let o=Object.getPrototypeOf(r);return o===Object.prototype?n:(o.constructor.name===s&&(o=Object.getPrototypeOf(o)),J(e,t,o,n))};function q(e,t,r){const n=[];for(const s in t){const o=t[s];for(const t of o){const{key:o}=t,a=H.get(e,s,r+o);if(!a||!a.length)throw new G(`Could not find registered handler for the operation ${r+o} under property ${s}`);const i=J(t,s,e);if(!i)throw new G("Missing handler arguments for decorators");for(const e of a){const t=H.getHandlerName(e),r=i[t];if(!r)throw new G("Missing handler arguments for handler "+t);const o=r.data;n.push({handler:e,data:[o],prop:[s]})}}}return n}function Z(e){const t=e.reduce((e,t)=>{if(!t||!t.data||!t.prop)throw new G("Missing decorator properties or data");if(!t.data[0].group)return e.set(Symbol(),t),e;const r=t.data[0].group;if(e.has(r)){const n=e.get(r);e.set(r,{handler:n.handler,data:[...n.data,...t.data],prop:[...n.prop,...t.prop]})}else e.set(r,{...t});return e},new Map),r=Array.from(t.values());return r.forEach(e=>{const t=e.data.map((t,r)=>({data:t,prop:e.prop[r]}));t.sort((e,t)=>(e.data.groupPriority??50)-(t.data.groupPriority??50)),e.data=t.map(e=>e.data),e.prop=t.map(e=>e.prop)}),r}function W(e){return e.sort((e,t)=>(e.data[0].priority??50)-(t.data[0].priority??50)),e}function X(e,t,r){return oe(U.CREATE_UPDATE,e,t,r)}function ee(e,t,r){return oe(U.UPDATE,e,t,r)}function te(e,t,r){return oe(U.CREATE,e,t,r)}function re(e,t,r){return oe(U.READ,e,t,r)}function ne(e,t,r){return oe(U.DELETE,e,t,r)}function se(e,t,r){return oe(U.ALL,e,t,r)}function oe(e=U.ALL,t,r,n){return pe(C.ON,e,t,r,n)}function ae(e,t,r){return fe(U.CREATE_UPDATE,e,t,r)}function ie(e,t,r){return fe(U.UPDATE,e,t,r)}function ce(e,t,r){return fe(U.CREATE,e,t,r)}function le(e,t,r){return fe(U.READ,e,t,r)}function ue(e,t,r){return fe(U.DELETE,e,t,r)}function de(e,t,r){return fe(U.ALL,e,t,r)}function fe(e=U.ALL,t,r,n){return pe(C.AFTER,e,t,r,n)}function pe(e,s=U.ALL,o,a,i=Q){return(c,l)=>{const u=c.constructor.name,d=s.reduce((n,s)=>{const d=e+s;let f=t.readOperation(c.constructor,l,d);f||(f={operation:s,handlers:{}});const p=H.getHandlerName(o);let h=i;if(a){if(Object.keys(a).filter(e=>e in i).length>0)throw new G("Unable to merge groupSort into dataToAdd due to overlaping keys");h={...i,...a}}return f.handlers[u]&&f.handlers[u][l]&&p in f.handlers[u][l]||(f.handlers[u]=f.handlers[u]||{},f.handlers[u][l]=f.handlers[u][l]||{},f.handlers[u][l][p]={data:h},n.push(((e,t)=>(r,n)=>{H.register(t,e,r,n)})(d,o),r(t.key(M.OPERATIONS,l,d),f))),n},[]);return n(...d)(c,l)}}function he(e,t){return(...r)=>s(e,{args:r,handler:t})}const Ee=e=>he(C.REFLECT+C.BLOCK,(e,t)=>e.includes(t))(e),ge=e=>he(C.REFLECT+C.BLOCK,e)();function ye(e){return(n,s)=>r(t.key(D.GENERATED,s),e||!0)(n,s)}function me(e,t,r,n,s){if(void 0===n[r])return;const o=d.hash(n[r]);s&&n[r]===o||(n[r]=o)}function Ae(){return n(X(me),r(D.HASH,{}))}function Te(e,t){const{args:r,type:n,prefix:s,suffix:o,separator:a,filterEmpty:i,hashResult:c}=t;try{const t=r.map(t=>{if("keys"===n)return t;if(void 0===e[t]){if(i){if(!Array.isArray(i))return;if(i.includes(t))return}throw new G(`Property ${r} does not contain a value to compose from`)}return e[t].toString()}).filter(e=>!i||!!e);s&&t.unshift(s),o&&t.push(o);const l=t.map(e=>"object"==typeof e&&"[object Object]"===e.toString()?JSON.stringify(e):e).join(a);return c?d.hash(l):l}catch(e){throw new G("Failed to compose value: "+e)}}function we(e,t,r,n){n[r]=Te(n,t)}function Oe(s,o=!1,a=b,i=!1,c="values",l="",u="",d={priority:55}){return e.for(D.COMPOSED).define({decorator:(e,s,o,a,c,l,u)=>(d,f)=>{const p={args:e,hashResult:s,separator:o,type:a,prefix:c,suffix:l,filterEmpty:i},h=[ye(D.COMPOSED),X(we,p,u),r(t.key(D.COMPOSED,f),p)];return s&&h.push(Ae()),n(...h)(d,f)},args:[s,o,a,c,l,u,d]}).apply()}function Pe(e,t=b,r=!1,n=!1,s="",o="",a={priority:55}){return Oe(e,n,t,r,"keys",s,o,a)}function ve(e,t=b,r=!1,n=!1,s="",o="",a={priority:55}){return Oe(e,n,t,r,"values",s,o,a)}function Re(e){return(t,r,n,s,o)=>{if(p.shouldGenerate(s,n,t))try{switch(e){case C.CREATE:s[n]=1;break;case C.UPDATE:if(t.get("applyUpdateValidation")&&o&&s[n]!==o[n])throw new z(`Version mismatch: ${s[n]} !== ${o[n]}`);s[n]++;break;default:throw new G("Invalid operation: "+e)}}catch(e){throw new G("Failed to update version: "+e)}}}function De(){const n=D.VERSION;return(s,o)=>e.for(n).define(r(t.key(n,o),!0),ye(D.VERSION),f(Number),te(Re(C.CREATE)),ee(Re(C.UPDATE))).apply()(s,o)}function be(){return e.for(D.TRANSIENT).define((e,n)=>{r(t.key(D.TRANSIENT,n),{})(e,n)}).apply()}function Se(t=L.READONLY.INVALID){const r=D.READONLY,n={message:t,description:"defines the attribute as readOnly",async:!1};return e.for(r).define({decorator:h,args:[Se,r,n]}).apply()}async function Le(e,t,r,n){p.shouldGenerate(n,r,e)&&(n[r]=e.timestamp)}function Ne(t=U.CREATE_UPDATE,s=S){const o=D.TIMESTAMP,a=u.updateKey(D.TIMESTAMP);return e.for(o).define({decorator:(e,t)=>{const s=[ye(D.TIMESTAMP),E(t,L.TIMESTAMP.DATE),g(L.TIMESTAMP.REQUIRED),r(u.key(D.TIMESTAMP),{operation:e,format:t}),oe(e,Le)];return-1!==e.indexOf(C.UPDATE)?s.push(r(a,{message:L.TIMESTAMP.INVALID})):s.push(Se()),n(...s)},args:[t,s]}).apply()}async function Ie(e,t,r,n){if(n[r])try{n[r]=t.serializer?(new t.serializer).serialize(n[r]):JSON.stringify(n[r])}catch(e){throw new Y(`Failed to serialize ${r.toString()} property of model ${n.constructor.name}: ${e}`)}}async function ke(e,t,r,n){if(n[r]&&"string"==typeof n[r])try{n[r]=t.serializer?(new t.serializer).deserialize(n[r]):JSON.parse(n[r])}catch(e){throw new Y(`Failed to deserialize ${r.toString()} property of model ${n.constructor.name}: ${e}`)}}function xe(e){return n(X(Ie,{serializer:e}),fe(U.ALL,ke,{serializer:e}),f([String,Object]),s(D.SERIALIZE,{serializer:e}))}function Ce(){return n(g(),Se(),(e,n)=>r(t.key(D.ID,n),{})(e,n))}function Me(e,r){const n=[];for(const s in e){if(!Object.prototype.hasOwnProperty.call(e,s)||r.includes(s))continue;const o=t.validationFor(e.constructor,s)||{};n.push({prop:s,decorators:o})}return n}function je(e,t,r,n,s){const o=u.get(n.key);if(!o)throw Error("Missing validator for "+n.key);if(!o.updateHasErrors)return T(void 0,s);if(!s&&n.async)return T(void 0,s);const a=Object.values(n)||{},i=o.updateHasErrors(e[r],t[r],...a);return T(i,s)}function Ue(e,t,r,n,s){const o={};for(const a in n){const i={...n[a],key:a};if(!s&&i.async)continue;let c=je(e,t,r,i,s);if(i.key===y.LIST&&(!c||s)){const n=e[r],o=t[r],a=n instanceof Set?[...n]:n,l=o instanceof Set?[...o]:o;if(a?.length){const e=[i.class||i.clazz||i.customTypes].flat().map(e=>((e=(e="function"!=typeof e||e.name?e:e()).name?e.name:e)+"").toLowerCase()),t=a.map(t=>{if(p.isModel(t)){const e=p.pk(t,!0);if(!e)return"Failed to find model id";const r=l.find(t=>e===p.pk(t,!0));return t.hasErrors(r)}return e.includes(typeof t)?void 0:"Value has no validatable type"});if(s)c=Promise.all(t).then(e=>e.every(e=>!e)?void 0:e);else{const e=t.every(e=>!e);c=t.length>0&&!e?t:void 0}}}c&&(o[i.key]=c)}if(!s)return Object.keys(o).length>0?o:void 0;const a=Object.keys(o),i=Object.values(o);return Promise.all(i).then(e=>{const t={};for(let r=0;r<e.length;r++){const n=e[r];void 0!==n&&(t[a[r]]=n)}return Object.keys(t).length>0?t:void 0})}function Fe(e,r,n,...s){const a=Me(r,s),i={},c={};for(const{prop:l,decorators:u}of a){const a=l+"",d=r[l],{designTypes:f}=t.getPropDesignTypes(r.constructor,l);if(!f)continue;if(f.some(e=>[Array.name,Set.name].includes(e))){if(!u||!Object.keys(u).includes(y.LIST)){i[a]={[y.TYPE]:`Array or Set property '${a}' requires a @list decorator`};continue}if(d&&!(Array.isArray(d)||d instanceof Set)){i[a]={[y.TYPE]:`Property '${l+""}' must be either an Array or a Set`};continue}}const h=Ue(r,e,a,u,n)||{},E=p.isPropertyModel(r,a);if(null!=d&&E){const t=d,r=f.map(e=>p.get(e.name||e)).find(e=>!!e),n=f.map(e=>"function"==typeof e?e.name?e.name.toLowerCase():e()?.name.toLowerCase():e.toLowerCase());if(r&&d instanceof r){const r=m(a,...s);c[a]=t.hasErrors(e[l],...r)}else n.includes(typeof d)||(h[y.TYPE]=r?"Value must be an instance of "+r.name:`Unable to verify type consistency, missing model registry for ${f.toString()} on prop ${a}`,delete h[o.TYPE])}(Object.keys(h).length>0||n)&&(i[a]=h),n||Object.entries(c[a]||{}).forEach(([e,t])=>{void 0!==t&&(i[`${a}.${e}`]=t)})}if(!n)return Object.keys(i).length>0?new A(i):void 0;const l=i,u=Object.keys(l),d=Object.values(l);return Promise.allSettled(d).then(async e=>{const t={};for(const[e,r]of Object.entries(c)){const n=await r;n&&Object.entries(n).forEach(([r,n])=>{void 0!==n&&(t[[e,r].join(".")]=n)})}for(let r=0;r<e.length;r++){const n=u[r],s=e[r];"fulfilled"===s.status&&void 0!==s.value?t[n]=s.value:"rejected"===s.status&&(t[n]=s.reason instanceof Error?s.reason.message:(s.reason||"Validation failed")+"")}return Object.keys(t).length>0?new A(t):void 0})}function He(e){return e.reduce((e,t,r)=>(t&&(e="string"==typeof e?e+`\n - ${r}: ${t.toString()}`:` - ${r}: ${t.toString()}`),e),void 0)}async function $e(e,t,r,n,s,o){const a=Ve(r,n,s);if(!a)return;const i=W(Z(q(r,a,s)));for(const s of i){const a=[t,s.data.length>1?s.data:s.data[0],s.prop.length>1?s.prop:s.prop[0],r];if([C.UPDATE,j.UPDATE_ALL].includes(n)){if(!o)throw new G("Missing old model for update operation");a.push(o)}try{await s.handler.apply(e,a)}catch(e){if(t.logger.for($e).error(`Failed to execute handler ${s.handler.name} for ${s.prop} on ${r.constructor.name}`),t.get("breakOnHandlerError"))throw e}}}function Ve(e,r,n){const s=n?.replace(/[.]$/,""),o=t.get(e.constructor,M.OPERATIONS);if(o)return Object.keys(o).reduce((e,t)=>{const n=s?o[t][s]||{}:o[t],a=Object.keys(n).filter(e=>e===r),i=[];for(const e of a)i.push({key:e,props:n[e]});return i&&i.length&&(e||(e={}),e[t]=i),e},void 0)}p.prototype.isTransient=function(){return t.isTransient(this)},p.prototype.hasErrors=function(e,...t){!e||e instanceof p||(t.unshift(e),e=void 0);const r=this.isAsync(),n=w(this,r,...t);return r?Promise.resolve(n).then(n=>n||!e?n:Fe(e,this,r,...t)):n||!e?n:Fe(e,this,r,...t)},p.prototype.segregate=function(){return p.segregate(this)},p.segregate=e=>{if(!t.isTransient(e))return{model:e};const r=t.validatableProperties(e.constructor),n=t.get(e.constructor,D.TRANSIENT),s={model:{},transient:{}};for(const t of r)if(Object.keys(n).includes(t)){s.transient=s.transient||{};try{s.transient[t]=e[t]}catch(e){throw new Y(`Failed to serialize transient property ${t}: ${e}`)}}else s.model=s.model||{},s.model[t]=e[t];return s.model=p.build(s.model,e.constructor.name),s},t.pk=((e,r=!1)=>{if(!e)throw Error("No model was provided");const n=e instanceof p?e.constructor:e,s=t.get(n,D.ID);if(!s)throw Error("No Id property defined for model "+(n?.name||"Unknown Model"));const o=Object.keys(s)[0];if(!r)return o;if(e instanceof p)return e[o];throw Error("Cannot get the value of the pk from the constructor")}).bind(t),p.pk=((e,r=!1)=>t.pk(e,r)).bind(p),p.pkProps=(e=>t.get(e,t.key(D.ID,p.pk(e)))).bind(p),p.isTransient=(e=>!!t.get("function"!=typeof e?e.constructor:e,D.TRANSIENT)).bind(p),p.composed=((e,r)=>{const n=e instanceof p?e.constructor:e;return r?t.get(n,t.key(D.COMPOSED,r)):!!t.get(n,D.COMPOSED)}).bind(p),p.merge=((e,t,r)=>{const n=e=>Object.entries(e).reduce((e,[t,r])=>(null!=r&&(e[t]=r),e),{});return new(r=r||e.constructor)(Object.assign({},n(e),n(t)))}).bind(p),t.saveOperation=((e,r,n,s)=>{r&&t.set(e,t.key(M.OPERATIONS,r,n),s)}).bind(t),t.readOperation=((e,r,n)=>{if(r&&n)return t.get(e,t.key(M.OPERATIONS,r,n))}).bind(t),t.isTransient=(e=>!!t.get("function"!=typeof e?e.constructor:e,D.TRANSIENT)).bind(t),p.generated=((e,r)=>!!t.get("function"!=typeof e?e.constructor:e,t.key(D.GENERATED,r))).bind(p),p.shouldGenerate=((e,t,r)=>!r.get("allowGenerationOverride")||void 0===e[t]).bind(p),p.versionProp=(e=>{const r=t.get(e.constructor);if(!r||!r[D.VERSION])throw new G("No version found for "+e.constructor.name);return Object.keys(r)[0]}).bind(p),p.versionOf=(e=>{const t=e[p.versionProp(e)];if("number"!=typeof t||1>t)throw new G("Invalid version number: "+t);return t}).bind(p);const _e={parentContext:void 0,childContexts:[],ignoredValidationProperties:[],callArgs:[],writeOperation:!1,affectedTables:[],operation:void 0,breakOnHandlerError:!0,rebuildWithTransient:!0,ignoreValidation:!1,ignoreHandlers:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0,allowGenerationOverride:!1},ze=e=>(new Ge).accumulate(Object.assign({},e,{timestamp:new Date,logger:e.logger||R.get()}));class Ge{constructor(e){this.cache=new v,Object.defineProperty(this,"cache",{value:e?e.cache:new v,writable:!1,enumerable:!1,configurable:!0})}static{this.factory=ze}accumulate(e){return Object.defineProperty(this,"cache",{value:this.cache.accumulate(e),writable:!1,enumerable:!1,configurable:!0}),this}get logger(){return this.cache.logger}get timestamp(){return this.cache.timestamp}get(e){try{return this.cache.get(e)}catch(t){const r=this.cache.parentContext;if(r)return r.get(e);throw t}}static childFrom(e,t){return Ge.factory(Object.assign({},e.cache,t||{}))}static async from(e,t,r,...n){return Ge.factory(Object.assign({},_e,t,{operation:e,model:r,logger:t.logger||R.get()}))}static async args(e,t,r,n,s){const o=r.pop();async function a(){return n?n.context(e,s||{},t,...r):Ge.from(e,s||{},t,...r)}let i;return o?o instanceof Ge?(i=o,r.push(o)):(r.push(o),i=await a(),r.push(i)):(i=await a(),r.push(i)),{context:i,args:r}}}function Ye(e,t,r,n){const s=n||t.name;e[s]=new Proxy(e[s],{apply:async(e,t,n)=>{let s=r.call(t,...n);return s instanceof Promise&&(s=await s),s=e.call(t,...s),s instanceof Promise&&(s=await s),s}})}function Ke(e,t,r,n){const s=n||t.name;e[s]=new Proxy(e[s],{apply:async(e,t,n)=>{let s=e.call(t,...n);return s instanceof Promise&&(s=await s),s=r.call(t,...s),s instanceof Promise&&(s=await s),s}})}function Be(e,t,r,n,s){const o=s||r.name;e[o]=new Proxy(e[o],{apply:async(e,r,s)=>{let o=t.call(r,...s);o instanceof Promise&&(o=await o);const a=o[o.length-1];if(!(a instanceof Ge))throw new G("Missing a context");let i=e.call(r,...o);return i instanceof Promise&&(i=await i),i=n.call(r,i,a),i instanceof Promise&&(i=await i),i}})}function Qe(e,t,r,n,s){const o=s||r.name;e[o]=new Proxy(e[o],{apply:async(e,r,s)=>{let o=t.call(r,...s);o instanceof Promise&&(o=await o);const a=o.pop(),i=o[o.length-1];if(!(i instanceof Ge))throw new G("Missing a context");if(i.get("applyUpdateValidation")&&!i.get("ignoreDevSafeGuards")&&!(a instanceof p)&&(!Array.isArray(a)||!a.every(e=>e instanceof p)))throw new G("No previous versions os models found");let c=e.call(r,...o);return c instanceof Promise&&(c=await c),c=n.call(r,c,a,i),c instanceof Promise&&(c=await c),c}})}class Je{get class(){if(!this._class)throw new G("No class definition found for this repository");return this._class}get pk(){return p.pk(this.class)}get pkProps(){return p.pkProps(this.class)}constructor(e){e&&(this._class=e);const t=this;[this.create,this.read,this.delete].forEach(e=>{const r=e.name;Be(t,t[r+"Prefix"],e,t[r+"Suffix"])}),Qe(t,t[this.update.name+"Prefix"],this.update,t[this.update.name+"Suffix"])}async createAll(e,...t){return Promise.all(e.map(e=>this.create(e,...t)))}async createPrefix(e,...t){const r=await Ge.args(C.CREATE,this.class,t);if(e=new this.class(e),r.context.get("ignoreHandlers")||await $e(this,r.context,e,C.CREATE,C.ON),!r.context.get("ignoreValidation")){const t=await Promise.resolve(e.hasErrors());if(t)throw new z(t.toString())}return[e,...r.args]}async createSuffix(e,t){return t.get("ignoreHandlers")||await $e(this,t,e,C.CREATE,C.AFTER),e}async createAllPrefix(e,...t){const r=await Ge.args(C.CREATE,this.class,t),n=r.context.get("ignoreHandlers"),s=r.context.get("ignoreValidation");if(e=await Promise.all(e.map(async e=>{const t=new this.class(e);return n||await $e(this,r.context,t,C.CREATE,C.ON),t})),!s){const t=He(await Promise.all(e.map(e=>Promise.resolve(e.hasErrors()))));if(t)throw new z(t)}return[e,...r.args]}async createAllSuffix(e,t){return t.get("ignoreHandlers")||await Promise.all(e.map(e=>$e(this,t,e,C.CREATE,C.AFTER))),e}async readAll(e,...t){return await Promise.all(e.map(e=>this.read(e,...t)))}async readSuffix(e,t){return t.get("ignoreHandlers")||await $e(this,t,e,C.READ,C.AFTER),e}async readPrefix(e,...t){const r=await Ge.args(C.READ,this.class,t),n=new this.class;return n[this.pk]=e,await $e(this,r.context,n,C.READ,C.ON),[e,...r.args]}async readAllPrefix(e,...t){const r=await Ge.args(C.READ,this.class,t);return await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,$e(this,r.context,t,C.READ,C.ON)})),[e,...r.args]}async readAllSuffix(e,t){return t.get("ignoreHandlers")||await Promise.all(e.map(e=>$e(this,t,e,C.READ,C.AFTER))),e}async updateAll(e,...t){return Promise.all(e.map(e=>this.update(e,...t)))}async updateSuffix(e,t,r){return r.get("ignoreHandlers")||await $e(this,r,e,C.UPDATE,C.AFTER,t),e}async updatePrefix(e,...t){const r=await Ge.args(C.UPDATE,this.class,t),n=r.context,s=r.context.get("ignoreHandlers"),o=r.context.get("ignoreValidation"),a=e[this.pk];if(!a)throw new G("No value for the Id is defined under the property "+this.pk);let i;if(n.get("applyUpdateValidation")&&(i=await this.read(a),n.get("mergeForUpdate")&&(e=p.merge(i,e,this.class))),s||await $e(this,r.context,e,C.UPDATE,C.ON,i),!o){const t=await Promise.resolve(e.hasErrors(i));if(t)throw new z(t.toString())}return[e,...r.args,i]}async updateAllPrefix(e,...t){const r=await Ge.args(C.UPDATE,this.class,t),n=r.context,s=n.get("ignoreHandlers"),o=n.get("ignoreValidation"),a=e.map(e=>{const t=e[this.pk];if(void 0===t)throw new G("No value for the Id is defined under the property "+this.pk);return t});let i;if(n.get("applyUpdateValidation")&&(i=await this.readAll(a,n),n.get("mergeForUpdate")&&(e=e.map((e,t)=>p.merge(i[t],e,this.class)))),s||await Promise.all(e.map((e,t)=>$e(this,r.context,e,C.UPDATE,C.ON,i?i[t]:void 0))),!o){let t;t=n.get("applyUpdateValidation")?await Promise.all(e.map((e,t)=>Promise.resolve(e.hasErrors(i[t])))):await Promise.resolve(e.map(e=>e.hasErrors()));const r=He(t);if(r)throw new z(r)}return[e,...r.args,i]}async updateAllSuffix(e,t,r){if(r.get("applyUpdateValidation")&&!r.get("ignoreDevSafeGuards")&&!t)throw new G("No previous versions of models provided");return r.get("ignoreHandlers")||await Promise.all(e.map((e,n)=>$e(this,r,e,C.UPDATE,C.AFTER,t?t[n]:void 0))),e}async deleteAll(e,...t){return Promise.all(e.map(e=>this.delete(e,...t)))}async deleteSuffix(e,t){return t.get("ignoreHandlers")||await $e(this,t,e,C.DELETE,C.AFTER),e}async deletePrefix(e,...t){const r=await Ge.args(C.DELETE,this.class,t),n=await this.read(e,...r.args);return await $e(this,r.context,n,C.DELETE,C.ON),[e,...r.args]}async deleteAllPrefix(e,...t){const r=await Ge.args(C.DELETE,this.class,t),n=await this.readAll(e,...r.args);return await Promise.all(n.map(async e=>$e(this,r.context,e,C.DELETE,C.ON))),[e,...r.args]}async deleteAllSuffix(e,t){return t.get("ignoreHandlers")||await Promise.all(e.map(e=>$e(this,t,e,C.DELETE,C.AFTER))),e}toString(){return this.class.name+" Repository"}}const qe="##VERSION##",Ze="##PACKAGE##";t.registerLibrary(Ze,qe);export{_ as BadRequestError,$ as BaseError,ge as BlockOperationIf,Ee as BlockOperations,V as BreakError,j as BulkCrudOperationKeys,B as ConflictError,Ge as Context,D as DBKeys,U as DBOperations,L as DEFAULT_ERROR_MESSAGES,S as DEFAULT_TIMESTAMP_FORMAT,ze as DefaultContextFactory,_e as DefaultRepositoryFlags,b as DefaultSeparator,G as InternalError,M as ModelOperations,K as NotFoundError,C as OperationKeys,H as Operations,F as OperationsRegistry,Ze as PACKAGE_NAME,I as ReadOnlyValidator,Je as Repository,Y as SerializationError,k as TimestampValidator,N as UpdateValidationKeys,x as UpdateValidator,qe as VERSION,z as ValidationError,fe as after,de as afterAny,ce as afterCreate,ae as afterCreateUpdate,ue as afterDelete,le as afterRead,ie as afterUpdate,Te as composeAttributeValue,ve as composed,we as composedFromCreateUpdate,Pe as composedFromKeys,$e as enforceDBDecorators,ye as generated,Ve as getDbDecorators,J as getHandlerArgs,q as getHandlersDecorators,Me as getValidatableUpdateProps,Z as groupDecorators,Ae as hash,me as hashOnCreateUpdate,Ce as id,oe as on,se as onAny,te as onCreate,X as onCreateUpdate,ne as onDelete,re as onRead,ee as onUpdate,pe as operation,Ye as prefixMethod,Se as readonly,He as reduceErrorsToPrint,xe as serialize,ke as serializeAfterAll,Ie as serializeOnCreateUpdate,W as sortDecorators,he as storeHandlerMetadata,Ke as suffixMethod,Ne as timestamp,Le as timestampHandler,be as transient,Fe as validateCompare,je as validateDecorator,Ue as validateDecorators,De as version,Re as versionCreateUpdate,Be as wrapMethodWithContext,Qe as wrapMethodWithContextForUpdate};
//# sourceMappingURL=db-decorators.js.map