Setup sanitization for a specific object structure.
A Schema defines the configurations of how objects should be sanitized.
instructions
Object? instructions on how to sanitize (optional, default{}
)
const ambitiousReg = /[!@#$%^&*()[\]<>:;/\\]/g;
const schema = new Schema({
title: {
remove: ambitiousReg,
transform: {
from: /[._-]/g,
to: ' '
},
convert: (input) =>
input.split(' ').map(i =>
i.charAt(0).toUpperCase() + i.substr(1).toLowerCase()
).join(' ')
},
slug: {
remove: ambitiousReg,
transform: {
from: /[\s._]/g,
to: '-'
},
convert: (input) => input.toLowerCase()
}
});
const subject = {
title: 'hell()O.woRld!',
slug: 'example: /h@ello_world'
};
const expected = {
title: 'Hello World',
slug: 'example-hello-world'
};
const actual = schema.sanitize(subject);
expect(actual).toMatchObject(expected);
Sanitize an object according to the instructions applied to the schema.
input
Object? object to sanitize
Returns Object a sanitized object
Get a property from the schema.
propName
string the property to select
Returns Object the property of the schema
Convert all plain JS objects to objects of the Property class.
instructions
Object object with properties
Returns Object object of properties with the supplied instructions
A property of the sanitization schema.
name
String the property name in the schemadefinition
(null | Object)? the definitions of the sanitizers this property uses (optional, defaultnull
)
const schema = new Schema({ foo: { remove: /\s?bar\s?/ } });
const property = schema.path('foo');
const expected = 'chair';
const subject = 'bar chair';
const actual = property.sanitize(subject);
expect(actual).toMatch(expected);
const expected = { foo: 'chair' };
const subject = { foo: 'bar chair' };
const actual = property.sanitizeObject(subject);
expect(actual).toMatchObject(expected);
Sanitize the input according to the schema property's definition.
input
any what to sanitize
Returns any the sanitized input
Sanitize a property of the input object what matches the schema property's name.
input
Object what to sanitize
Returns Object the input object with only the relevant property sanitized