Skip to content

[Feature Request] Allow certain rules to be run only within certain contexts #486

@jeffsawatzky

Description

@jeffsawatzky

Feature description:
For an API I am trying to design, I would like to support Create/Patch style requests that have exactly the same payloads, except the Create doesn't require an ID (and should reject the request if provided) and the Patch doesn't have any required fields other than ID.

Problem it solves or use case:
I don't want to have to maintain multiple separate message payloads, and the validation rules on each field across those messages, when the payloads are pretty much identical. There would be a lot of duplication across the validation rules, which can lead to issues down the line.

Proposed implementation or solution:
Allow a way to specify the contexts in which a rule should be applied, and then when you validate a message you can specify the context in which to validate.
A naive, not fully fleshed out, approach could be to create new rules that take the rule plus a list of contexts for which the rule would be applied:

edition = "2023";

package bufbuild.people.v1;

import "buf/validate/validate.proto";
import "bufbuild/people/v1/predefined_string_rules.proto";

message Person {
  string id = 1 [
    (buf.validate.field).ctx_required = {rule: true, ctx: "patch"} // Only required for Patch requests
  ];
  string name = 2 [
    (buf.validate.field).ctx_required = {rule: true, ctx: "create"}, // Only required for Create requests
    (buf.validate.field).string.min_len = 1, // Required for all requests
    (buf.validate.field).string.ctx_max_len = {rule:256, ctx: "create", ctx: "patch"} // Required for create/patch requests
  ];
}

The context ids above are free text, but maybe a hard coded enum, or an int so that user can use a custom defined enum might be better?
Then, when you call validate you could pass a single/list of contexts for which to validate against.

Contribution:
I can try to do some of this stuff once the schema has been defined and approved. I can help implement the python side of things of needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions