Starcounter-Jack / JSON-Patch

Lean and mean Javascript implementation of the JSON-Patch standard (RFC 6902). Update JSON documents using delta patches.
MIT License
1.81k stars 215 forks source link

Disallow patching specific valid paths #249

Closed AaronJY closed 8 months ago

AaronJY commented 4 years ago

Is there a way to disallow an operation against a path that exists in my document, but that I specifically want to disallow updating? For example, an ID or created date field.

I wrote a custom validator that does this for me, using a custom error name. This all seems very messy, and I'd love to see this functionality built-in 👍

const galleryPatchDocumentValidator: Validator<Gallery> = (operation: Operation, index: number, document: Gallery, existingPathFragment: string) => {
        // Firstly, use the built-in validator to validate things like
        // whether the given paths exist
        const defaultValidationError: JsonPatchError = validate(operations, document);
        if (defaultValidationError) {
            throw defaultValidationError;
        }

        // Then, ensure only set paths are being validated
        switch (operation.path)
        {
            case "/name":
            case "/visibility":
                break;

            default:
                throw new JsonPatchError(`Not allowed to patch path ${operation.path}`, 'OPERATION_PATH_INVALID', index, operation, document);
        }
    }

Apologies if I've missed any documentation on how to do this. I've had a good read through and can't find anything that explicitly mentions how to do this within the bounds of the package/without wiring together a custom validator like this.

Edit: Ideally it'd be great if we could specify a collection of paths alongside a specific list of operations we wan't to allow.

For example, I want to allow replace on path /name but don't want to allow remove

Love this package!

Starcounter-Jack commented 4 years ago

Thanks for the feedback. There is no built-in functionality for this. I think it is well suited for a separate pass before applying the patch. A router like radix tree with rights would be a good candidate maybe?