schema-tools
schema-tools copied to clipboard
The sanitize function does not seem to be working with nested objects
All the given examples in this repo for sanitization are either json schemas representing objects with keys and string or integer values or a couple of examples where the key has a value of an array where the array then holds multiple objects.
All that is fine, but, I haven't had any success if the object is nested. That's when a key inside the main object is yet another object. I have tried multiple variations of writing the schema including the same approach as given in the examples for an array but the nested object's values never gets sanitized.
Has anybody ever had a similar issue? am I confusing something in here?
Take a look at the following snippet
const name: CustomFormat = {
name: 'name',
description: 'Custom name format',
detect: /^[A-Z][a-z]+$/,
defaultValue: 'Buddy',
};
const exampleFormats: CustomFormats = {
name,
};
const schema: JsonSchema = {
title: 'TestSchema',
type: 'object',
additionalProperties: false,
properties: {
names: {
title: 'TestNames',
type: 'object',
properties: {
first: {
type: 'string',
format: 'name',
},
middle: {
type: 'string',
format: 'name',
},
last: {
type: 'string',
format: 'name',
},
},
required: ['first', 'middle', 'last'],
},
},
required: ['names'],
};
const o = {
names: {
first: 'Bob',
middle: 'Charles',
last: 'Miller',
},
};
const result = sanitizeBySchema(schema, getDefaults(exampleFormats))(o);
console.log({ result });
This logged result
is exactly the same as the original object and this does not work. Similarly, I have also tried writing properties of the schema as follows:
properties: {
names: {
title: 'Names',
type: 'object',
items: {
title: 'TestTitle',
type: 'string',
properties: {
first: {
title: 'First',
type: 'string',
format: 'name',
},
middle: {
title: 'Middle',
type: 'string',
format: 'name',
},
last: {
title: 'Last',
type: 'string',
format: 'name',
},
},
},
},
},
This also doesn't have any effect.
@bahmutov @amirrustam I would really appreciate your input on this. Thank you guys in advance.
Update
I have confirmed the above described limitation. In fact, the sanitize
function literally checks for the value either being a string or an array to process. These tools doesn't work with any values in the json object that are not strings. Another observation that I have made is that if the backend's response contains an integer or any non string value, the santize
function will simply ignore that too. What's the logic behind it? Why not literally, simply, replace the value by the defaultValue
defined in the CustomFormat
?
This is truly surprising that such an obvious limitation exist. Can someone shed some light here please? @brian-mann @bahmutov ?