Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

request: schema support #48

Open
productdevbook opened this issue Nov 7, 2022 · 1 comment · May be fixed by #104
Open

request: schema support #48

productdevbook opened this issue Nov 7, 2022 · 1 comment · May be fixed by #104

Comments

@productdevbook
Copy link

productdevbook commented Nov 7, 2022

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 } }
@productdevbook productdevbook changed the title schema support request: schema support Nov 7, 2022
@darvids0n
Copy link

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 }
}

ferferga added a commit to ferferga/defu that referenced this issue Aug 27, 2023
Fixes unjs#48

Minor code improvement by using optional chaining as well when
checking for merger function
ferferga added a commit to ferferga/defu that referenced this issue Aug 27, 2023
@ferferga ferferga linked a pull request Aug 27, 2023 that will close this issue
8 tasks
ferferga added a commit to ferferga/defu that referenced this issue Oct 25, 2023
ferferga added a commit to ferferga/defu that referenced this issue Jan 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants