json-schema-org / json-schema-vocabularies

Experimental vocabularies under consideration for standardization
53 stars 9 forks source link

`immutable` keyword #31

Open silverwind opened 4 years ago

silverwind commented 4 years ago

JSON schema has readOnly and writeOnly to specify static read/write access to a property but sometimes it's useful to have immutable properties that can only be written once and only read thereafter.

For example a POST request could accept a value (property acts writeOnly) and for subsequent request the property acts readOnly similar to immutable variables in many programming languages.

I think a immutable keyword would be a useful meta-data addition that validators can generally ignore unless they have knowledge whether the validated data is considered "new" in which case it could fail validation when it's not new and a value for an immutable property is present.

karolzlot commented 2 years ago

I think readOnly is exactly for this use case (to mark field in API to which client can't write to, so it's immutable field).

You just need to have more than one schema. E.g. one for creating entity, and second for getting it and updating it. (I think schema for getting and updating can be usually the same)

gregsdennis commented 2 years ago

Additionally, you can also mark an object as read-only.

{
  "type": "object",
  "properties": {
    ...
  },
  "readOnly": true
}

This, to me, says that the entire object is immutable.

Since readOnly is an annotation only, it's the application's responsibility to enforce it, whether it's on a property or the object.

dchandekstark commented 7 months ago

I am sympathetic to this issue, although I'm not sure what the right solution is. The problem IMO is that writeOnly defines a property that cannot be retrieved. The semantics just feel counterintuitive. It appears that the only way -- with a single schema -- to make a property once-writable and retrievable (like setting the value of a primary key in a RDBMS table) is to define the property as readOnly, and that also feels weird, since the client should then have no expectation that the value is settable, and the application has to know, separately from the schema, what the real semantics are in any case. 🤷