o-development / ldo

Monorepo for Linked Data Objects (ldo)
MIT License
23 stars 5 forks source link

Feature Request: Option for validation on `#from[Subject|Object|Json]` #24

Open jeswr opened 3 months ago

jeswr commented 3 months ago

Hi @jaxoncreed - nice work on ldo!

If I have the shape https://github.com/jeswr/ldo-validation-repro/blob/0c078511d63f5a8225133dbc90a524a382eaa75e/shapes/shape.shex#L4-L6 and then execute the code https://github.com/jeswr/ldo-validation-repro/blob/0c078511d63f5a8225133dbc90a524a382eaa75e/test.ts#L4-L9 subject.prop is typed as a string by the typescript types; but is actually undefined when the code is run due to the fact that the input data does not conform to the shape. This can be seen by cloning this repro and running npm i && npm run build && npm t.

In this case I would have expected an error during the call #fromSubject with a validation taking place to ensure that the dataset conforms to the shape. I would like to request a feature to support this validation behavior which is enabled by default from the next major version.

jeswr commented 3 months ago

FWIW doing the following seems to work in the subject case

import { LdoBase, ShapeType, createLdoDataset } from "@ldo/ldo";
import { DatasetCore, NamedNode } from "@rdfjs/types";
import RdfJsDb from "@shexjs/neighborhood-rdfjs";
import { ShExValidator } from "@shexjs/validator";

function shapeFromDataset<T extends LdoBase>(shapeType: ShapeType<T>, dataset: DatasetCore, subject: NamedNode) {
    const validator = new ShExValidator(shapeType.schema, (RdfJsDb as any).ctor(dataset));
    const validationResult = validator.validateShapeMap([{
        node: subject.value,
        shape: shapeType.shape,
    }]);
    if (validationResult[0].status !== 'conformant') {
        throw new Error('Subject does not conform to shape');
    }
    return createLdoDataset([...dataset]).usingType(shapeType).fromSubject(subject);
}