defu
defu copied to clipboard
request: schema support
By default, giving a schema, If the incoming new data is the same key, append the new data to the values of the schema keys. delete keys that are not compatible with the schema.
Example
const schema = {
isPro: false,
darkMode: false,
pages: {
home: false,
settings: false,
},
}
const result = defu(schema, { isPro: 'bbb', d: 'c', pages: { home: true } }, {schema: true})
console.log(result) // {isPro: 'bbb', darkMode: false, pages: { home: true, settings: false } }
This is actually pretty trivially implemented using a custom defu already. Try something like this:
import {createDefu} from "defu";
const testSchema = {
isPro: false,
darkMode: false,
pages: {
home: false,
settings: false,
},
}
const testInput = { isPro: 'bbb', d: 'c', pages: { home: true } }
const schemaDefu = createDefu((schema, key, _value) => {
// this func requires ESNext or ES2022 dialect
// otherwise use e.g. !Object.keys(schema).includes(key)
if (!Object.hasOwn(schema, key))
{
// skip merging in the value - it's not in the schema
return true;
}
// use defu's default merging behaviour otherwise
return false;
})
const result = schemaDefu(testInput, testSchema)
console.log(result);
My output from the above is:
{
isPro: 'bbb',
darkMode: false,
pages: { home: true, settings: false }
}