package file→ .shtukbase/packages/collections/checks/s03_required.ts
checks/s03_required.ts
42 lines, 1.9 KB.
- // S3. Required fields from the schema: `required: true` — always; `requiredWhen: {field: [values]}` — when the value
- // of that field (usually status) is in the list. Every record needs a title.
- import { addr, ctx, empty, hole, scopeAll, values } from './lib/schemalib.ts';
- import { type Project, type Result, pystr } from './lib/speclib.ts';
- import { main } from './lib/runner.ts';
- export const RULE = { id: 's03', title: 'Schema: required fields are filled', scope: 'all records of all collections: title, required, requiredWhen' };
- export function check(p: Project, res: Result): void {
- const c = ctx(p);
- const cols = scopeAll(c, res, 'required fields');
- if (!res.part('required fields', null)) return;
- for (const coll of cols) {
- const rules: [string, Record<string, any> | null][] = [];
- for (const [name, spec] of Object.entries(c.props(coll))) {
- if (!spec || typeof spec !== 'object' || Array.isArray(spec)) continue;
- if (spec.required === true) rules.push([name, null]);
- const when = spec.requiredWhen;
- if (when && typeof when === 'object' && !Array.isArray(when) && Object.keys(when).length) rules.push([name, when]);
- }
- for (const r of c.records(coll)) {
- const a = addr(r.id);
- if (empty(r.fm.title)) hole(res, a, 'title', 'missing', 'no title', 'fill in the title of the record');
- for (const [name, when] of rules) {
- if (!empty(r.fm[name])) continue;
- if (!when) {
- hole(res, a, name, 'missing', `the required field ${name} is not filled`, `fill in ${name}`);
- continue;
- }
- for (const [f, vals] of Object.entries(when)) {
- const cur = r.fm[f];
- if (!empty(cur) && values(vals).map(pystr).includes(pystr(cur))) {
- hole(res, a, name, 'missing-when', `${f} = ${pystr(cur)}, but the field ${name} is empty`, `fill in ${name}`);
- break;
- }
- }
- }
- }
- }
- }
- if (import.meta.main) main({ RULE, check });