UNPKG

@casl/mongoose

Version:

Allows to query accessible records from MongoDB based on CASL rules

3 lines (2 loc) 1.64 kB
import{rulesToQuery as t,AccessibleFields as n}from"@casl/ability/extra";import{wrapArray as r}from"@casl/ability";import o from"mongoose";function e(t){const n=t.conditions;return t.inverted?{$nor:[n]}:n}const c={$expr:{$eq:[0,1]}};class s{constructor(t,n){this.t=t;this.o=n}ofType(n){const r=t(this.t,this.o,n,e);return r===null?c:r}}function i(t,n="read"){return new s(t,n)}function u(t,n,r){const o=n.detectSubjectType({constructor:t.model});if(!o)throw new TypeError(`Cannot detect subject type of "${t.model.modelName}" to return accessible records`);const e=i(n,r).ofType(o);return t.and([e])}function f(t,n){return u(this.where(),t,n)}function a(t,n){return u(this,t,n)}function l(t){t.query.accessibleBy=a;t.statics.accessibleBy=f}const h=t=>Object.keys(t.paths);function m(t,n){const o=n.getFields(t);if(!n||!("except"in n))return o;const e=r(n.except);return o.filter((t=>e.indexOf(t)===-1))}function p(){let t;return(n,o)=>{if(!t){const e=o&&"only"in o?r(o.only):m(n,o);t=()=>e}return t}}function d(t,r){const o=Object.assign({getFields:h},r);const e=p();function c(r,c){return new n(r,c||"read",e(t,o)).of(this)}function s(r,c){const s={constructor:this};return new n(r,c||"read",e(t,o)).of(s)}t.statics.accessibleFieldsBy=s;t.method("accessibleFieldsBy",c)}const w=t=>{const n=typeof t==="string"?o.models[t]:t;if(!n)throw new Error(`Unknown mongoose model "${t}"`);return"schema"in n?Object.keys(n.schema.paths):[]};function b(t,r="read"){return new n(t,r,w)}export{i as accessibleBy,b as accessibleFieldsBy,d as accessibleFieldsPlugin,l as accessibleRecordsPlugin,h as getSchemaPaths}; //# sourceMappingURL=index.mjs.map