rest-layer icon indicating copy to clipboard operation
rest-layer copied to clipboard

schema: Allow FieldSerializer to be called on AllOff/Dict/Object members

Open smyrman opened this issue 6 years ago • 1 comments

This issue is split out from #182, but the problem is the same. For schema.AllOff, if one or more of the members implement as a FieldSerialzier, it should be called in a sensible manner.

Let's discuss a littlebit what the most common use-case for schema.AllOf is before we jump to a soultion. In my mind, the most obvious use-case for AllOf is to validate both a common and a variable set of fields, e.g. something like this:

Validator: &schema.AllOf{
  &schema.Object{Schema: &commonSchema},
  &schema.AnyOf{
      &schema.Object{Schema: &schemaA},
      &schema.Object{Schema: &schemaB},
  },
}

where commonSchema defines a set of common fields that apply to all items, while schemaA and schemaB describes e.g. a schema for what's valid when say a field "type" is equal either "A" or "B":

var (
  schemaA = schema.Schema{
    Fields: {
      "type": {Validator: &schema.String{Allowed: []string{"A"}}},
      ...
    },
  }
  schemaB = schema.Schema{
    Fields: {
      "type": {Validator: &schema.String{Allowed: []string{"B"}}},
      ...
    },
  }
)

That means, presumably, that for FieldSerializer selection on AllOf to be useful:

  1. We also want nested types like Array, Dict, Object to implement FieldSerializer to call serialization on any sub-field that might implement it while ignoring any fields it doesn't know about.
  2. We want to call all FieldSerializers that are found in schema, passing in the output of the previous FieldSerializer as input to the next.

smyrman avatar Mar 19 '18 09:03 smyrman

PS! It would be the user's responsibility to make sure that fields do not overlap between the different all-off members. E.g. if specifying a &schema.AllOf{&schema.Dict{...}, &schema.Object{...}}, and both the dict and object has members that implements FieldSerializers, it's the user's responsibility to add a KeysValidatorthat prevents the dict entry from serializing fields that should be serilized by the object. The same would of-course already be true for Validation, so it should not be unreasonable to assume and document this behaviour.

smyrman avatar Mar 19 '18 09:03 smyrman