All files / lib/utils getMinimalFields.ts

92% Statements 23/25
80% Branches 16/20
100% Functions 5/5
95.24% Lines 20/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 391x 1x     1x           194x     194x 194x 255x 255x 255x   194x   86x 76x   10x 10x     86x 104x 100x   84x     86x     1x
import { AnyAbility, detectSubjectType } from "@casl/ability";
import { mergeArrays } from "feathers-utils";
import { GetMinimalFieldsOptions } from "../types";
 
const getMinimalFields = (
  ability: AnyAbility, 
  action: string, 
  subject: Record<string, unknown>, 
  options: GetMinimalFieldsOptions): string[] => 
{
  Iif (options.checkCan && !ability.can(action, subject)) {
    return [];
  }
  const subjectType = detectSubjectType(subject);
  const rules = ability.possibleRulesFor(action, subjectType).filter(rule => {
    const { fields } = rule;
    const matched = rule.matchesConditions(subject);
    return fields && matched;
  });
  if (rules.length === 0) { return options.availableFields || []; }
  let fields: string[];
  if (options.availableFields) {
    fields = options.availableFields;
  } else {
    fields = rules.find(x => !x.inverted)?.fields;
    Iif (!fields) { return []; }
  }
 
  rules.forEach(rule => {
    if (rule.inverted) {
      fields = fields.filter(x => !rule.fields.includes(x));
    } else {
      fields = mergeArrays(fields, rule.fields, "intersect");
    }
  });
  return fields;
};
 
export default getMinimalFields;