ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/collections/checks/s03_required.ts

checks/s03_required.ts

42 líneas, 1.9 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // S3. Required fields from the schema: `required: true` — always; `requiredWhen: {field: [values]}` — when the value
  2. // of that field (usually status) is in the list. Every record needs a title.
  3. import { addr, ctx, empty, hole, scopeAll, values } from './lib/schemalib.ts';
  4. import { type Project, type Result, pystr } from './lib/speclib.ts';
  5. import { main } from './lib/runner.ts';
  6. export const RULE = { id: 's03', title: 'Schema: required fields are filled', scope: 'all records of all collections: title, required, requiredWhen' };
  7. export function check(p: Project, res: Result): void {
  8. const c = ctx(p);
  9. const cols = scopeAll(c, res, 'required fields');
  10. if (!res.part('required fields', null)) return;
  11. for (const coll of cols) {
  12. const rules: [string, Record<string, any> | null][] = [];
  13. for (const [name, spec] of Object.entries(c.props(coll))) {
  14. if (!spec || typeof spec !== 'object' || Array.isArray(spec)) continue;
  15. if (spec.required === true) rules.push([name, null]);
  16. const when = spec.requiredWhen;
  17. if (when && typeof when === 'object' && !Array.isArray(when) && Object.keys(when).length) rules.push([name, when]);
  18. }
  19. for (const r of c.records(coll)) {
  20. const a = addr(r.id);
  21. if (empty(r.fm.title)) hole(res, a, 'title', 'missing', 'no title', 'fill in the title of the record');
  22. for (const [name, when] of rules) {
  23. if (!empty(r.fm[name])) continue;
  24. if (!when) {
  25. hole(res, a, name, 'missing', `the required field ${name} is not filled`, `fill in ${name}`);
  26. continue;
  27. }
  28. for (const [f, vals] of Object.entries(when)) {
  29. const cur = r.fm[f];
  30. if (!empty(cur) && values(vals).map(pystr).includes(pystr(cur))) {
  31. hole(res, a, name, 'missing-when', `${f} = ${pystr(cur)}, but the field ${name} is empty`, `fill in ${name}`);
  32. break;
  33. }
  34. }
  35. }
  36. }
  37. }
  38. }
  39. if (import.meta.main) main({ RULE, check });