UNPKG

@casl/mongoose

Version:

Allows to query accessible records from MongoDB based on CASL rules

72 lines (60 loc) 1.47 kB
import { AccessibleFields as t, rulesToCondition as n } from "@casl/ability/extra"; import r from "mongoose"; function o(t) { const n = t.conditions; return t.inverted ? { $nor: [ n ] } : n; } const e = { and: t => ({ $and: t }), or: t => ({ $or: t }), empty: () => ({}) }, c = { $expr: { $eq: [ 0, 1 ] } }; var s = class { constructor(t, n) { this.t = t, this.o = n; } ofType(t) { const r = this.t.rulesFor(this.o, t), s = n(r, o, e); return null === s ? c : s; } }; 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 h(t) { t.query.accessibleBy = a, t.statics.accessibleBy = f; } const m = t => { const n = "string" == typeof t ? r.models[t] : t; if (!n) throw new Error(`Unknown mongoose model "${t}"`); return "schema" in n ? Object.keys(n.schema.paths) : []; }; function p(n, r = "read") { return new t(n, r, m); } export { i as accessibleBy, p as accessibleFieldsBy, h as accessibleRecordsPlugin }; //# sourceMappingURL=index.mjs.map